【发布时间】:2019-03-05 23:01:12
【问题描述】:
我按照this 示例使用 django 设置了 create-react-app。网页在这样的视图中传递:
def get(self, request):
try:
with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f:
return HttpResponse(f.read())
我现在正在尝试将 conext (conext = {'foo':'bar'}) 传递给它。
我尝试通过get_context_data:
class MyView(DetailView):
"""
Serves the compiled frontend entry point (only works if you have run `yarn
run build`).
"""
def get(self, request):
try:
with open(os.path.join(settings.MY_VIEW_DIR, 'build', 'index.html')) as f:
return HttpResponse(f.read())
except FileNotFoundError:
return HttpResponse(
"""
This URL is only used when you have built the production
version of the app. Visit http://localhost:3000/ instead, or
run `yarn run build` to test the production version.
""",
status=501,
)
def get_context_data(self, *args, **kwargs):
context = super(MyView. self).get_context_data(*args, **kwargs)
context['message'] = 'Hello World!'
return context
我也试过把网页变成模板然后返回
return render(request, 'path/to/my/index.html', {'foo':'bar'})
但这只是返回没有我的反应代码的页面。
有没有更好的方法来使用 django 实现 create-react-app 或将反应代码转换为模板?
【问题讨论】:
标签: django reactjs django-context