在 django 中从单个视图渲染多个模板 [英] render multiple template from a single view in django
问题描述
我想将上下文数据发送到一个 html 并想呈现不同的 html.登录后用户被重定向到此仪表板视图.在这里我想渲染两个 html 文件,上下文值将被发送到一个 html 假设 temp1.html 文件,但用户可以看到 temp2.html 文件.在 temp2.html 和其他 html 文件中,我将包含 temp1.html 文件.有什么办法吗?视图.py
I want to send context data to one html and want to render different html. After login user is redirected to this dashboard view. Here I want to render two html file, the context value will be sent to one html let say temp1.html file, but user can see temp2.html file. In temp2.html and other html file, I will include temp1.html file. Is there any way to do so? views.py
def dashboard(request):
print('in dashboard view')
object = UserSelection.objects.get(user=request.user)
if object.user_type == 'candidate':
val_cand = CandidateDetail.objects.filter(candidate_username=request.user)
if val_cand:
print('Candidate filled data') #Already filled data
data = CandidateDetail.objects.get(candidate_username=request.user)
return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
else:
print('new user') #Registered but not filled data
return render(request, 'dashboard.html', {'obj':object.user_type})
else:
val_emp = EmployerDetail.objects.filter(name=request.user)
if val_emp:
print('Employer filled data') #Already filled data
data = EmployerDetail.objects.get(name=request.user)
return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
else:
print('new user') #Registered but not filled data
return render(request, 'dashboard.html', {'obj':object.user_type})
推荐答案
你不能在一个视图中渲染两个 html 文件.请为所需的行为使用 Django 模板语言.
You can't render two html file in single view. Please use the Django template language for the desired behaivour.
i.e) 如果您将 obj
传递给 dashboard.html
并且在 html 文件中也可以访问 obj.
i.e) If your passing obj
to dashboard.html
and inside html files can also access obj.
dashboard.html
{{ obj }}
{% include 'test1.html' %}
{% include 'test2.html' %}
您可以使用关键字参数向模板传递额外的上下文:
You can pass additional context to the template using keyword arguments:
{% include 'test1.html' with obj=obj additional_context='blah' %}
test1.html
{{ obj }}
这篇关于在 django 中从单个视图渲染多个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!