我有一个 django View ,它返回一个变量以便在模板中呈现
return render_to_response('index.html', {
'courses': courses})
我正在使用 ReactJS 来呈现 index.html 文件,但我不确定我是否必须指向 View 中的 index.html 或 ReactJS 文件。
如果我必须指向 index.html,我该如何将类(class)变量与 React 一起使用?
更新 我正在传递的可变类(class)是 dictionnary 类型
最佳答案
模板处理先于任何类型的 JavaScript 解释。这意味着您必须在某种意义上模拟其在 js 标签之间的硬编码。
首先,要知道客户端接收到的python字典很可能已经损坏。为防止这种情况,您可能希望将其作为 json 对象发送。这意味着,在编写 views.py 脚本时,您必须 json.dumps
您的字典。如下
from django.shortcuts import render
import json
#...
#...
return render(request,
'your_app/index.html',\
{'courses': json.dumps(courses)}\
)
请注意,我使用 render
而不是 render_to_response
,因为 render
is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext
另外,请注意您必须指向您的 index.html,但确切的路径取决于您项目的结构。以上,我假设您遵循了推荐的 django 项目布局,即
myproject/
manage.py
your_project/
__init__.py
urls.py
wsgi.py
settings/
__init__.py
base.py
dev.py
prod.py
your_app/
__init__.py
models.py
managers.py
views.py
urls.py
templates/
your_app/
index.html
[...]
然后,在html端,
...
<script>
var courses = {{courses|safe}}
// working with the variable courses
</script>
...
现在,你可以用它做你想做的事,用 ReactJS 就可以了图书馆。
关于django - 从 Django View 传递数据以使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927944/