【发布时间】:2020-10-15 14:44:51
【问题描述】:
这只是一个关于 Django 的问题。我有两个视图,我将两个上下文渲染到两个视图。如何将两个上下文渲染到同一个 HTML 模板?
【问题讨论】:
标签: html django django-rest-framework django-templates
这只是一个关于 Django 的问题。我有两个视图,我将两个上下文渲染到两个视图。如何将两个上下文渲染到同一个 HTML 模板?
【问题讨论】:
标签: html django django-rest-framework django-templates
如果我正确理解您的问题,您可以在渲染时在两个视图函数中调用相同的模板文件:
def your_view_1(request):
context_1: dict = {'key': 'a_string_depending_on_request_or_view'}
return render(request, 'common_template.html', context_1)
def your_view_2(request):
context_2: dict = {'key': 'another_string'}
return render(request, 'common_template.html', context_2)
【讨论】:
urlpatterns = [path('path-1/', views.your_view_1, name='view-name-1'), path('path-2/', views.your_view_2, name='view-name-2'),]
def view_1(request):
context_1: dict = {
//Your key/value pairs
check = False
}
return render(request, 'common_template.html', context_1)
def view_2(request):
context_2: dict = {
//Your other key value pairs
check = True
}
return render(request, 'common_template.html', context_2)
然后在你的模板中,你可以做一个 if-else
{% if check %}
//do stuff related to view2
{% else %}
//do stuff related to view1 %}
{%endif%}
【讨论】: