if
{% if d.age > 20 %} {% if d.age < 50 %} <h1>{{ d.name }}的年龄大于20小于50</h1> {% else %} <h1>hello{{ d.name }}</h1> {% endif %} {% elif d.age > 10 %} <h1>{{ d.name }}的年龄大于10小于20</h1> {% else %} <h1>{{ d.name }}的年龄小于10</h1> {% endif %}
for
{% for name in l %} <h1> {{ forloop.counter0 }}:{{ name }}</h1> <h1> {{ forloop.revcounter0 }}:{{ name }}</h1> {% endfor %}
for 里面可以放 empty
{% for name in l %} {% if forloop.first %} <li class="first"> {% else %} <li> {% endif %} {{ name }} </li> {% empty %} <h1>没有相关文章</h1> {% endfor %}
autoescape
# 传递的上下文信息 context = { "info":"<a href='www.baidu.com'>百度</a>" } # 模板中关闭自动转义 {% autoescape off %} {{ info }} {% endautoescape %}
如果把off
改成on
,那么就会显示成一个普通的字符串。示例代码如下:
{% autoescape on %}
{{ info }}
{% endautoescape %}
自定义filter和simple_tag
------a、在app中创建templatetags模块(必须的)
------b、创建任意 .py 文件,如:my_tags.py
from django import template from django.utils.safestring import mark_safe register = template.Library() #register的名字是固定的,不可改变 @register.filter def filter_multi(v1,v2): return v1 * v2 @register.simple_tag def simple_tag_multi(v1,v2): return v1 * v2 @register.simple_tag def my_input(id,arg): result = "<input type='text' id='%s' class='%s' />" %(id,arg,) return mark_safe(result)
------c、在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tags.py :{% load my_tags %}
------d、使用simple_tag和filter(如何调用)
-------------------------------.html {% load xxx %} #首行 # num=12 {{ num|filter_multi:2 }} #24 {{ num|filter_multi:"[22,333,4444]" }} {% simple_tag_multi 2 5 %} 参数不限,但不能放在if for语句中 {% simple_tag_multi num 5 %}
------e、在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag.