html内部布局和我在其他页面扩展,所有工作都很好,但类别菜单(来自数据库)隐藏在一些页面,我可以看到它只是在一个页面有我的代码:
def produit_list(request):
produits = Produits.objects.all()
categories = Category.objects.all()
context = {
'produits':produits,
'categories':categories,
}
return render(request, 'shop.html', context)
#categories.html
<div class="col-md-4 pt-5">
<h2 class="h2 text-light border-bottom pb-3 border-light">Categories</h2>
<ul class="list-unstyled text-light footer-link-list">
{% for cat in categories %}
<li><a class="text-decoration-none" href="#">{{cat.name}}</a></li>
{% endfor %}
</ul>
</div>
我将此代码包含在base.html
中我想知道如何加载它在所有的网站像菜单在每一页的底部,现在我可以看到它只是在shop.html。
谢谢
通过上下文处理程序执行
# Create a context_processors.py in your django app
def produit_list(request):
produits = Produits.objects.all()
categories = Category.objects.all()
context = {
'produits':produits,
'categories':categories,
}
# Return a dictionary with the data you want to load
# on every request call or every page.
return context
在你的设置中:
# ...
TEMPLATES = [
{
# ...
"OPTIONS": {
"context_processors": [
# ...
"your_app.context_processors.produit_list",
# ...
],
},
}
]
# ...
然后你可以在你想要的每个页面调用产品和类别,就像你在你的categories.html中做的那样
您可以使用自定义上下文处理器来完成此操作或者使用自定义模板标签.
1-通过自定义上下文处理器传递
创建自定义上下文处理器文件和函数。
# the custom_context.py file
def global_ctx():
return {
# any other values ...
"categories": Category.objects.all(),
}
将此文件添加到TEMPLATES
部分下的settings.py
文件中
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"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",
"App_Name.custom_context.global_ctx", # Custom Context Processor
],
},
},
]
和你是好的去,你可以访问categories
在你所有的模板文件。
2-通过自定义标签传递
在你的应用下创建一个templatetags
目录。并在其中创建自定义标记文件。
# the your_app/templatetags/custom_tag.py file
from django import template
register = template.Library()
@register.simple_tag
def get_categories():
return Category.objects.all()
然后在您的html
文件中,首先加载自定义标记{% load custom_tag %}
,然后您可以访问它。这可以帮助你更多地了解自定义模板标签和过滤器。