Python - Django - simple_tag 和 inclusion_tag

simple_tag:

simple_tag 和自定义 filter 类似,但可以接收更多更灵活的参数

在 app01/templatetags/ 目录下创建 mysimple_tag.py

mysimple_tag.py:

from django import template
register = template.Library()


@register.simple_tag(name="cal")
def cal(arg1, arg2, arg3, arg4):
    return "{}+{}+{}+{}".format(arg1, arg2, arg3, arg4)

test.html:

{% load mysimple_tag %}

{% cal "abc" "def" "ghi" "jkl" %}

运行结果:

inclusion_tag:

多用于返回 html 代码

在 app01/templatetags/ 目录下创建 myinclusion_tag.py

myinclusion_tag.py:

扫描二维码关注公众号,回复: 6897347 查看本文章
from django import template
register = template.Library()


@register.inclusion_tag("result.html")
def show_results(n):
    n = 1 if n < 1 else int(n)
    data = ["第{}项".format(i) for i in range(1, n+1)]
    return {"data": data}

result.html:

<ul>
  {% for choice in data %}
    <li>{{ choice }}</li>
  {% endfor %}
</ul>

test.html:

{% load myinclusion_tag %}

{% show_results 10 %}

运行结果:

猜你喜欢

转载自www.cnblogs.com/sch01ar/p/11266420.html