问题
.
is my project root, where manage.py
resides. I have a base template at ./templates/base.html
. I have a custom template tag in ./app/templatetags/mytags.py
from django import template
register = template.Library()
@register.unread_tag
def get_unread(user):
return user.notification_set.filter(viewed=False).count()
How do I make this tag usable for base.html, from which all app-level templates inherit.
回答1:
Your tag definition is not correct. You need to use register.simple_tag decorator:
@register.simple_tag(name='unread')
def get_unread(user):
return user.notification_set.filter(viewed=False).count()
Then, you need to load the tag into the template:
{% load mytags %}
Then, you can use the tag in the template:
{% unread request.user %}
回答2:
Quite an old question but things have changed since this was asked.
You can load a custom tag for ALL templates within the project in settings.py
using the key builtins
in OPTIONS
of settings.TEMPLATES
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(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',
],
'builtins': [
'app.templatetags.mytags',
],
},
}]
You can read more about the options in the Django doc - DjangoTemplates of built-in backends.
This option is supported from Django 1.9 onwards.
来源:https://stackoverflow.com/questions/24288646/how-to-use-a-custom-template-tag-in-base-html