别名Django模板标签

时间:2013-01-10 02:50:19

标签: django django-templates

所以我经常在Django模板中使用以下内容:

{% include "conname.html" %}

我希望能够只拥有自己的标签,只需输入类似

的内容
{% conname %}

是否有一种简单的方法来设置某种别名,以便模板引擎在看到conname标记时,它知道实际上应该是特定的包含标记?

1 个答案:

答案 0 :(得分:0)

非常简单,在一个模块中只需添加以下代码(我的通常称为custom_tags.py:

from django import template

register = template.Library()

@register.simple_tag
def conname():
    return '''{% include "conname.html" %}'''

#to make it available everywhere (i generally add this to my urls.py
from django.template.loader import add_to_builtins
#this will be aded to all templates
add_to_builtins('custom_tags')

在您的模板中,您只需使用{% conname %} 或者你可以把它变得更复杂,并以编程方式调用IncludeNode,但这样就太过分了。