django templatetag? [英] django templatetag?
问题描述
如何使用django应用程序的模板?
how to use the templatetag of django app?
推荐答案
创建一个新的模板标签可能会涉及到什么是否是块标记(开始和结束 - 如 {%if%} {%endif%}
等)基本上,您需要创建一个 example.templatetags
模块(其中示例
是您的应用程序),其实现您的标签,然后 {%load example%}
在您的模板中,以便他们可以查看您的模板标签和过滤器。
Creating a new template tag can be quite involved depending on what it does, and whether or not it is a block tag (with a start and an end -- like {% if %} {% endif %}
, etc.) Basically, you need to create a example.templatetags
module (where example
is your application) which implements your tag, and then {% load example %}
in your templates so that they can "see" your template tags and filters.
例如,如果您要创建一个 {%foobarbaz%}
标签,该标签输出foor或bar或baz(作为arg给出)或(当给出任何其他东西)当在模板中使用时,您的示例/ templatetags.py
可能如下所示:
For example, if you want to create a {% foobarbaz %}
tag which outputs the either "foor" or "bar" or "baz" (when given as the arg) or "" (when anything else is given) when used in a template, your example/templatetags.py
might looks like this:
from django import template
register = template.Library()
@register.simple_tag
def foobarbaz(input):
if "foo" == input:
return "foo"
if "bar" == input:
return "bar"
if "baz" == input:
return "baz"
return ""
在你的模板中,你可能会这样做(记住上述模块是示例
应用程序的一部分):
In your templates, you might do something like this (remembering that the above module is part of the example
application):
{% load example %}
{% foobarbaz "bar" %}
{% foobarbaz "elephant" %}
{% foobarbaz "foo" %}
哪个输出:
bar
foo
请注意,因为我使用 simple_tag
,我只能简单地控制参数的解析,没有办法做结束标签等。
Note that, as I'm using simple_tag
, I have only rudimentary control over the parsing of arguments, there's no way to do an end tag, etc.
有关自定义模板过滤器和标签的文档获取更多信息。
这篇关于django templatetag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!