Django如何重用所有视图通用的视图功能
我有一个Django模板,我们称之为index.html,它分为3部分(页眉、内容和页脚)。在标题部分,我有一个搜索栏,其中包括一个下拉菜单,允许用户从中选择一个选项,并根据所选选项搜索内容。我希望标题部分包含在我未来的所有视图/模板中,并且仍然显示包含所有选项的下拉菜单 这是我当前视图文件中的内容Django如何重用所有视图通用的视图功能,django,django-templates,django-views,Django,Django Templates,Django Views,我有一个Django模板,我们称之为index.html,它分为3部分(页眉、内容和页脚)。在标题部分,我有一个搜索栏,其中包括一个下拉菜单,允许用户从中选择一个选项,并根据所选选项搜索内容。我希望标题部分包含在我未来的所有视图/模板中,并且仍然显示包含所有选项的下拉菜单 这是我当前视图文件中的内容 def index(request): return render( request, 'home.html'
def index(request):
return render(
request,
'home.html',
{'categories': get_all_categories()}
)
def cart(request):
return render(request, 'cart.html', {'categories': get_all_categories()})
def help(request):
return render(request, 'help.html', {'categories': get_all_categories()})
def about(request):
return render(request, 'about.html', {'categories': get_all_categories()})
def contact(request):
return render(request, 'contact.html', {'categories': get_all_categories()})
def search(request):
return render(request, 'search.html', {'categories': get_all_categories()})
def get_all_categories():
return Category.objects.all()
这是我的cart.html
{%extends“index.html”%}
{%block content%}
我的手推车
{%endblock%}
这就是contact.html的功能
{%extends“index.html”%}
{%block content%}
接触
{%endblock%}
这就是home.html包含的内容
{%extends“index.html”%}
{%block content%}
家
{%endblock%}
现在可以了,但我想知道是否有更好的方法来解决这个问题,这样我就不必在所有视图中重复相同的代码。您可以编写一个自定义代码,在渲染的每个模板中包含该变量
例如,编写一个上下文处理器,如下所示(在context\u processors.py
中):
并将其包含在设置.py中:
TEMPLATES = [
...
'OPTIONS': {
'context_processors': [
...
'myapp.context_processors.category_context_processor',
],
},
}
现在,变量categories
在您呈现的每个模板中都可用(无论如何,使用呈现
调用或请求上下文
),而不管您实际从视图传递的上下文是什么。您也可以使用模板标记
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
在您的poll_extras.py文件中
from django import template
register = template.Library()
@register.simple_tag
def get_categories(request, arg1, arg2, ...):
return {
'categories': get_all_categories(),
}
或者,您可以将包含标记与其自己的模板一起使用(在所有视图中保持不变):
最后,在模板中,您需要加载templatetag并使用它:
{% load poll_extras %}
您可以查看有关templatetags的更多信息,我认为这是一个优势。
TEMPLATES = [
...
'OPTIONS': {
'context_processors': [
...
'myapp.context_processors.category_context_processor',
],
},
}
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
from django import template
register = template.Library()
@register.simple_tag
def get_categories(request, arg1, arg2, ...):
return {
'categories': get_all_categories(),
}
@register.inclusion_tag('categories_block_template.html')
def get_categories(arg1, arg2, *args, **kwargs):
categories = Category.objects.filter(field1=arg1, ...)
...
{% load poll_extras %}