工作中Django总结之三(模板标签)

django中的模板标签

if/else 标签

(1)基本语法格式:

{% if condition %}
    ...display
{% endif %}    

(2)或者:

{% if condition1 %}
    ...display 1
{% elif condition2 %}
    ...display2
{% else %}
    ...display 3
{% endif %}            

(3)if标签支持and,or,not关键字来对多个变量做判断,或者对变量取反(not):

{% if athlete_list and coach_list %}
    athletes和coaches变量都可以用的。
{% endif %}

for标签

(1):

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}    

(2)在标签中添加一个reversed使该列表被反向迭代:

{% for athlete in athlete_list reversed %}
{% endfor %}

(3)for循环可以嵌套

{% for athlete in athlete_list %}
    {% for sport in athlete.sport_played %}
    {% endfor %}
{% endfor %}    

ifequal/ifnotequal标签
这个标签是比较两个值,当相等时,显示标签之中的所有值:

{% ifequal value1 value2 %}
    <h1>显示所有value1,value2相等的值</h1>
{% endifequal %}    

该标签支持else标签:

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}

注释标签

{# #}

过滤器

模板过滤器可以在变量被显示前修改它,过滤器使用管道字符:
{{ name|lower }}
{{ my_list|first|upper }} –多次过滤
{{ bio|truncatewords:”30” }} –带参数的过滤器

include标签

include标签允许在模板中包含其他的模板的内容

{% include “nav.html” %}

猜你喜欢

转载自blog.csdn.net/marslover521/article/details/68946528