How to use a custom template tag in base.html

对着背影说爱祢 提交于 2020-01-24 13:03:30

问题


. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!