django template模板的总结(一些高级用法,如嵌套,动态链接)

django 模板系统 有很多标签,其中cycle我觉得不好理解,至少网上文档也不好理解。

这些标签可以通过渲染模板文件而获得我们预期的效果和文字,常用的有如下这些标签:

标签:{% 标签名 %}
{% if 变量 %}  支持not or and,空对象空的玩意0默认为False
{% else %}
{% endif %}


{% for x in 变量名 %}      for 的forloop变量,有如下:counter,counter0,revcounter,revcounter0,first,last,parentloop
{% empty %}
{% endfor %}

{% ifequal 变量一 变量二 %}
{% else %}
{% endifequal %}

python的字典,列表,布尔,不能作为模板的比较量
{% ifnotequal %}
{% else %}
{% endifnotequal %}

过滤器:
用管道符,first(取得第一个字符),lower,upper,truncatewords(显示变量的前三十个词)
    addslashes(添加反斜杠到,任何反斜杠,单引和双引号),length(长度,个数)
    data(格式化datatime对象,例子:{{ pub_data|data:"F j,Y" }})
    过滤器,看附录F
有参数的话直接冒号接参数,如:“参数”

{% block %}
{% endblock %}

{% comment %}
{% endcomment %}

{% crsf_taken %}
防止crsf攻击

{% autoescape off%}{% endautoescape %}关闭自动转义,django默认会对传入模板的特殊符号进行转义,为了安全起见

一、多层嵌套

Django Python Template Nested List using For Loop

How to iterate over nested dictionaries in django templates

Nested for loop in Django Template not able to loop through a dictionary item

Nested loop in Django template

二、创建动态的template name动态链接

How to concatenate strings in django templates?

三、multiple filter in template 

How to apply multiple filters on a Django template variable?

原文地址:https://www.cnblogs.com/lxgbky/p/13808719.html