如何获取上下文使用Django
问题描述:
反应,我需要获取上下文中使用Django 反应,但我不能做到这一点如何获取上下文使用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)
但不渲染和表现出野生错误:(
未捕获的ReferenceError:TITULO没有定义
答
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>
然后在阵营可以参考context.variable
得到你所需要的价值。
谢谢! :')Muchas gracias !! –