如何使用django获得上下文反应 [英] how get context react using django

查看:97
本文介绍了如何使用django获得上下文反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用django
获得上下文响应,但我无法做到

i need get context in react using django but i cant do it

这是我的jsx中的代码

this is my code in my 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)

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

but does not render and wild error appeared :(

未捕获的ReferenceError:未定义titulo

Uncaught ReferenceError: titulo is not defined

推荐答案

Django上下文仅在呈现模板时出现在服务器上。React使用Javascript,这意味着它已在浏览器上呈现 。如果您想在React应用中使用Django变量,则需要在Javascript中设置这些变量(一定要在导入 bundle.js 之前这样做)。

The Django context is only when the template is rendered on the server. React uses Javascript which means it's rendered on the browser. If you want to use Django variables in your React app, you will need to set those variables in Javascript (making sure to do so before bundle.js is imported).

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

So your template might look something like this:

{% 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 获得所需的价值。

Then in React you can reference context.variable to get the value you need.

这篇关于如何使用django获得上下文反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆