如何在base.html中使用自定义模板标签 [英] How to use a custom template tag in base.html
本文介绍了如何在base.html中使用自定义模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.
是我的项目根目录, manage.py
所在的位置.我在 ./templates/base.html
中有一个基本模板.我在 ./app/templatetags/mytags.py
.
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()
如何使此标记可用于base.html,所有应用程序级模板都将从该标记继承.
How do I make this tag usable for base.html, from which all app-level templates inherit.
推荐答案
您的标签定义不正确.您需要使用 注册.simple_tag
装饰器:
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()
然后,您需要 load
标记插入模板:
Then, you need to load
the tag into the template:
{% load mytags %}
然后,您可以在模板中使用标记:
Then, you can use the tag in the template:
{% unread request.user %}
这篇关于如何在base.html中使用自定义模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文