【问题标题】:how get context react using django如何使用 django 获取上下文反应
【发布时间】:2023-03-07 05:08:01
【问题描述】:

我需要在使用 django 时获取上下文 但我做不到

这是我的代码 在我的 jsx 中

<h1>{{titulo}}</h1>
<h2>{{ejemplo}}</h2>

在我的模板中:

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body >
<div id="app"></div>
<script type="text/javascript" src="{% static 'bundle.js' %}"></script>
</body>
</html>

在我看来py:

def registro (request,giro):
    reg = 'Registro Normal'
    if giro==1:
        reg='Registro Especial'

    context = {
        'ejemplo':'tests',
        'titulo':reg
    }
    return render(request,'home/registro.html',context)

但不渲染并出现错误:(

未捕获的引用错误:未定义标题

【问题讨论】:

    标签: python django reactjs


    【解决方案1】:

    Django 上下文仅在模板被渲染时在服务器上。 React 使用 Javascript,这意味着它在浏览器上呈现。如果您想在您的 React 应用程序中使用 Django 变量,您需要在 Javascript 中设置这些变量(确保在导入 bundle.js 之前这样做)。

    所以你的模板可能看起来像这样:

    {% load staticfiles %}
    <!DOCTYPE html>
    <html>
    <head>
        <title>Index</title>
    </head>
    <body >
    <div id="app"></div>
    
    <script type="text/javascript">
      /* Put your context vars here. I recommend putting them under 
         a variable to avoid naming conflicts. 
      */
      var context = {
        titulo: '{{titulo}}',
        ejemplo: '{{ejemplo}}'
      };
    </script>
    
    <script type="text/javascript" src="{% static 'bundle.js' %}"></script>
    </body>
    </html>
    

    然后在 React 中你可以引用context.variable 来获取你需要的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2019-07-17
      • 2020-12-24
      • 2019-12-19
      相关资源
      最近更新 更多