我在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或将反应代码转换为模板的方法?
我认为答案是将其转换为模板而不是传递静态文件。
settings.MY_VIEW_DIR
是建立的index.html
的路径,所以我把它传递到settings.py
中的模板加载器:
MY_VIEW_DIR = os.path.join(BASE_DIR, "path","to","my","build","folder")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
MY_VIEW_DIR
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
有了这个,我可以在视图中使用它:
def get(self, request):
return render(request, 'build/index.html', {'foo':'bar'})
它的工作原理。