python - 如何使用 Django 获取上下文 react

标签 python django reactjs

我需要使用 django 获取上下文以使用react 但我做不到

这是我的代码 在我的 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)

但不渲染并且出现错误:(

Uncaught ReferenceError :标题未定义

最佳答案

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 来获取你需要的值。

关于python - 如何使用 Django 获取上下文 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456959/

相关文章:

python - django - handler404 与 handler500

javascript - 使用 Javascript 或 Jquery 将参数传递给 url

python - 从静态文件夹检索图像时如何防止 404 错误

javascript - 可变 reducer 的 Redux 初始状态

javascript - 下面的 React.js 代码中 "this"中的关键字 "this.state"指的是什么?

python - 按对象的类型排序

python - AbstractEventLoop.slow_callback_duration 的异步 python 日志记录细节

javascript - React-google-maps 中带孔的多边形

python - Flask-WTForms - 简单的 CRUD 示例 - 值不填充表单

python - 从给定的脚本文件中检索哈希 bang/shebang