Django第六天

1.模板层

模版语法重点:

  变量:{{ 变量名 }}

    1 深度查询 用句点符

    2 过滤器

  标签:{{%  % }}

2.过滤器

  {{  第一个参数 | 过滤器名字:第二个参数 }}

  {{ name | default:'数据为空‘}}None变量可以为空

  {{ person_list | default:length }}计算长度,只有一个参数,对字符串和列表都有效

  {{ 1024 | filesizeformat:}}计算文件大小

  {{ 'hello world lqz' | slice:''2:-1'' }}2表示从前面取,-1从后面取不到

  {{ value | date:''Y-m-d''}}

  {{ X |add:''-2'' }}可以字符串数字之间的加

  {{ value |truncatechars:''4''}}如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。

  {{ value |truncatewords:''4''}}截断文字

  {{ value |safe }}django模板会对html,js等语法自动转义,用safe过滤器不会转义,会解析这些语法。

3.标签

  标签看起来像是这样的: {% tag %}。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。一些标签需要开始和结束标签 (例如{% tag %} ...标签 内容 ... {% endtag %})。

 

FOR标签:遍历每一个元素:

{% for person in person_list %}
    <p>{{ person.name }}</p>
{% endfor %}

可以利用{% for obj in list reversed %}反向完成循环。

遍历一个字典:

{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

注:循环序号可以通过{{forloop}}显示  

复制代码
forloop.counter            The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
forloop.counter0           The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
forloop.revcounter         The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
forloop.revcounter0        The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
forloop.first              True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
forloop.last               True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)
forloop.parentloop 本层循环的外层循环
复制代码

for ... empty

for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

if 标签

{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

复制代码
复制代码
{% if num > 100 or num < 0 %}
    <p>无效</p>
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}
    <p>凑活吧</p>
{% endif %}
复制代码
复制代码

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。

with

使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的

例如:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

猜你喜欢

转载自www.cnblogs.com/AllenZhou/p/9946529.html