我需要使用 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/