![](/img/trans.png)
[英]django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 24: 'trans'. Did you forget to register or load this tag?
[英]django.template.exceptions.TemplateSyntaxError: Invalid block tag. Did you forget to register or load this tag?
我有一個包含上下文數據的視圖,它擴展了 base.html 但因為我希望上下文數據顯示在從 base.html 擴展的所有模板中,而不僅僅是包含上下文數據的視圖,我正在使用自定義模板標簽里面的上下文,但我得到一個錯誤。
使用和不使用上下文數據查看:
class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
paginate_by = 25
class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
paginate_by = 25
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
categories = Category.objects.all()
news = News.objects.all()
context.update({
'categories' : categories,
'news' : news,
})
return context
base.html 有和沒有自定義標簽
{% news %}
{% for new in news %}
<p>{{ new.title }}</p>
{% endfor %}
自定義標簽文件 templatetags/news.py
from django import template
from support.models import News
register = template.Library()
@register.inclusion_tag('news.html', takes_context=True)
def news(context):
return {
'news': News.objects.order_by("-date_posted")[0:25],
}
自定義標簽文件templatetags/news.html
{% for new in news %}
<p>{{ new.title }}</p>
{% endfor %}
文件結構:
項目
主要的
模板/主要
模板標簽
模型.py
網址.py
視圖.py ...
項目
...
很簡單,你應該在注冊的 news.html 模板中load
模板標簽。
只需在news.html
模板中加載標簽:
{% load tag_name %} #Add here tag name to load
注意:請確保在 settings.py 文件中添加模板標簽設置
您需要在settings.py
的TEMPLATES
變量中定義包含您的標簽代碼的 python 代碼。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(BASE_DIR.joinpath('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',
],
'libraries':{
'tagname': 'appname.news', # your template tag
}
},
},
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.