Django中的内置Tags

Dates

  • {% now %}

    {% now "m/d/Y" %}
    
copyright {% now 'Y' as current_year %}

该tag也可以接受Django的date 变量,比如{% now 'SHORT_DATETIME_FORMAT' %}--> 09/05/2020 10:59 p.m.

{% now 'SHORT_DATE_FORMAT' %}-->09/05/2020

{% now 'DATE_FORMAT' %}-->Sept. 5, 2020

Forms

tag里使用{% csrf_token %}来防止跨域伪造请求攻击。

比较操作

  • {% if %}和{% elif %}和{% else %}

    与python 语法类似,不再赘述

  • {% first of %}是一个输出第一个不是空的变量的快捷用法。

    #urls.py
    {'var1':'','var2':1,'var3':2 }
    
    {% firstof var1 var2 var3 %}
    

    {% if %},{% elif %}的等效方法:

    #firstof example
    {% firstof var1 var2 var3 %}
    
    #Equivalent of firstof example
    {%if var1 %}
    {{ var1|safe }}
    {% elif var2 %}
    {{ var2|safe }}
    {% elif var3 %}
    {{ var3|safe }}
    {% endif %}
    
    # Firstof example with a default value in case of no match( that is meaning all variables are empty)
    {% firstof var1 var2 var3 'All vars are empty' %}
    
    #Assign the firstof result to another variable
    {% firstof var1 var2 var3 as resultof %}
    
  • {% if in %}, {% if not in %}

  • {% if is value %}, {% if is not value %}

  • {% if value| %}

    比如:

    #urls.py
    {'drinklist':['coco','cola','milk'],'userdrink':'cola'}
    
    {% if drinklist|random == userdrink %}
    Yes it is 
    {% else %}
    No 
    {% endif %}
    

需要注意的是,在{% if %}里不允许有“()”,比如{% if drink in specials or drink== drink_of_day %},不能写成 {% if (drink in specials) or (drink== drink_of_day) %}

Loops

  • {% for %},以及带{% empty %}的{% for %}

    #urls.py
    {'drinks':['cola','coco','water']}
    
    #html
    {% for drink in drinks %}
    {{ drink }}
    {% endfor %}
    
#urls.py
{'drinks':[]}
{% for drink in drinks %}
{{ drink }}
{% empty %}
No drinks here
{% endfor %}

{% for %}也产生了一系列变量来对遍历过程进行控制:

Variable Description
forloop.counter The current iteration of the loop(1-indexed)
forloop.counter0 The current iteration of the loop(0-indexed)
forloop.revcounter The number of the iterations from the end of the loop(1-indexed)
forloop.revcounter0 The number of the iterations from the end of the loop(0-indexed)
forloop.first True,if it's the first time through the loop
forloop.last True,if it's the last time through the loop
#urls.py
'drinks':['water','cola','coco','milk']
#html
{% for drink in drinks %}
<b>{{ drink }}</b><br>
forloop.counter-->{{ forloop.counter }}<br>
forloop.counter0-->{{ forloop.counter0 }}<br>
forloop.revcounter0-->{{ forloop.revcounter0 }}<br>
forloop.revcounter-->{{ forloop.revcounter }}<br>
forloop.first-->{{ forloop.first }}<br>
forloop.last-->{{ forloop.last }}<br>
{% empty %}
No drinks here
{% endfor %}

  • {% cycle %}

    (1)一般放在{% for %}内,循环时,依次取其参数,如:

    #urls.py
    'drinks':['water','cola','coco','milk','coffee','wanglaoji']
    
    #base.html
    <!DOCTYPE html>
    <head>
        <title>
            {% block title_block %}
            Base 
            {% endblock %}
        </title>
        <style>
            .red {
                color:red;
            }
            .blue {
                color:blue;
            }
            .yellow {
                color:yellow;
            }
        </style>
    </head>
    <body>
        {% block body_block %}
        {% endblock %}
    </body>
    
    #rendered.html
    {% extends 'banners/base.html' %}
    {% block title_block %}
    test 
    {% endblock %}
    
    {% block body_block %}
    <url>
        {% for drink in drinks %}
        <li class="{% cycle 'red' 'yellow' 'blue' %}">{{ drink }}</li>
    </url>
    {% endfor %}
    {% endblock %}
    

    drink在drinks中循环时,每次循环,依次取'red',‘yellow','blue',然后周而复始,如下:

{% cycle %} 的参数也可以是变量,如将上述urls.py和rendered.html换成如下,效果一样:

#urls.py
'drinks':['water','cola','coco','milk','coffee','wanglaoji'],'r':'red','b':'blue','y':'yellow'
#rendered.html
{% extends 'banners/base.html' %}
{% block title_block %}
test 
{% endblock %}

{% block body_block %}
<url>
    {% for drink in drinks %}
    <li class="{% cycle r y b %}">{{ drink }}</li>
</url>
{% endfor %}
{% endblock %}

(2){% cycle arg1 arg2 .. as cc %}

{% cycle %}也不一定必须要在{% for %}内,也可以放在{% for %}外,在这种情况下,每次调用{% cycle arg1,arg2 %}都返回arg1,这样就达不到循环的目的了,怎么办?此时,正是{% cycle arg1 arg2 ... as cc %} 出现的原因了,as 将{% cycle arg1 arg2 ... %} "另存为" cc,之后的事情就比较有意思: 直接调用cc将只得到上次循环后的值,也就是说如果是“保存完" cc后,直接调用cc,将返回arg1,如果 {% cycle cc %}将”迫使“ cc进行循环,这时返回arg2,如果再直接调用cc呢,将返回arg2。代码的话,见下面:

# urls.py
'drinks':['water','cola','coco','milk','coffee','wanglaoji'],'r':'red','b':'blue','y':'yellow'
{% extends 'banners/base.html' %}
{% block title_block %}
test 
{% endblock %}

{% block body_block %}
<url>
    <li class="{% cycle r y b  %}">test1</li>

    <li class="{% cycle r y b %}">test4</li>
    <li class="{% cycle r y b %}">test5</li>
</url>
<p>以上每次都调用'{% cycle r y b %} ' 都将是第一个参数,而不能依次取后面参数的值</p>
<url>
    <li class="{% cycle r y b as testas %}">test1</li><span>("另存为testas")</span>
    <li class="{{ testas }}">test2</li><span>(直接调用testas)</span>
    <li class="{{ testas }}">test3</li><span>(直接调用testas)</span>
    <li class="{% cycle testas %}">test4</li><span>("强迫循环")</span>
    <li class="{{ testas }}">test5</li><span>(直接调用testas)</span>
    <li class="{{ testas }}">test6</li><span>(直接调用testas)</span>
    <li class="{% cycle testas %}">test7</li><span>("强迫循环")</span>
    <li class="{{ testas }}">test8</li><span>(直接调用testas)</span>
</url>
{% endblock %}

在cc后添加 ”silent", 即{% cycle arg1 arg2 ... as cc silent %},然后再{% cycle cc %}时,将只是个“强迫”循环的声明,而不返回任何值,见下:

#rendered.html 
{% extends 'banners/base.html' %}
{% block title_block %}
test 
{% endblock %}

{% block body_block %}
<url>
    <li class="{% cycle r y b  %}">test1</li>

    <li class="{% cycle r y b %}">test4</li>
    <li class="{% cycle r y b %}">test5</li>
</url>
<p>以上每次都调用'{% cycle r y b %} ' 都将是第一个参数,而不能依次取后面参数的值</p>
<url>
    <li class="{% cycle r y b as testas silent %}">test1</li><span>("仅声明循环")</span>
    <li class="{{ testas }}">test2</li><span>(直接调用testas)</span>
    <li class="{{ testas }}">test3</li><span>(直接调用testas)</span>
    <li class="{% cycle testas %}">test4</li><span>("声明循环,不返回任何值")</span>
    <li class="{{ testas }}">test5</li><span>(直接调用testas)</span>
    <li class="{{ testas }}">test6</li><span>(直接调用testas)</span>
    <li class="{% cycle testas %}">test7</li><span>("声明循环,不返回任何值")</span>
    <li class="{{ testas }}">test8</li><span>(直接调用testas)</span>
</url>
{% endblock %}
  • {% resetcycle %}

    重新设置循环,将循环值重新设定为第一个,如:

    #  rendered.html
    {% extends 'banners/base.html' %}
    {% block title_block %}
    test 
    {% endblock %}
    
    {% block body_block %}
    <url>
        <li class="{% cycle r y b  %}">test1</li>
    
        <li class="{% cycle r y b %}">test4</li>
        <li class="{% cycle r y b %}">test5</li>
    </url>
    <p>以上每次都调用'{% cycle r y b %} ' 都将是第一个参数,而不能依次取后面参数的值</p>
    <url>
        <li class="{% cycle r y b as testas %}">test1</li><span>("仅声明循环")</span>
        <li class="{{ testas }}">test2</li><span>(直接调用testas)</span>
        <li class="{{ testas }}">test3</li><span>(直接调用testas)</span>
        <li class="{% cycle testas %}">test4</li><span>("声明循环,不返回任何值")</span>
        <li class="{{ testas }}">test5</li><span>(直接调用testas)</span>
        
        <li class="{{ testas }}">test6</li><span>(直接调用testas)</span>
        {% resetcycle %}
        <p>resetcycle,下次循环不再是蓝色,而将是第一个值也就是红色</p>
        <li class="{% cycle testas %}">test7</li><span>("声明循环,不返回任何值")</span>
        <li class="{{ testas }}">test8</li><span>(直接调用testas)</span>
    </url>
    {% endblock %}
    
  • {% regroup %}

    regroup 有点像 pandas里的groupby ,即通过某个属性将一群数据进行分组,不同的是该tag分组后会自动生成两个属性:①grouper:item that was grouped ② list: a list of all items in this group

    # urls.py
    stores=[
        {'name':'Downtown','street':'385 Main street','city':'San Diego'},
        {'name':'Uptown','street':'231 Highland avenue','city':'San Deiego'},
        {'name':'Midtown','street':'85 Balboa street','city':'Los Angeles'},
        {'name':'Downtown','street':'639 Spring street','city':'Los Angeles'},
        {'name':'Midtown','street':'1407 Broadway street','city':'Los Angeles'},
    ]
    'stores':stores
    
    # rendered.html
    {% regroup stores by city as city_list %}
    <ul>
        {% for city in city_list %}
        <li>{{ city.grouper }}</li>
        <ul>
            {% for item in city.list %}
            <li>{{ item.name }}:{{ item.street }}</li>
            {% endfor %}
        </ul>
        {% endfor %}
    </ul>
    

Python and Filter Operations

  • {% filter %}

    可将包在{% filter %}....{% endfilter %}的部分内容全部进行过滤。

    #urls.py
    'drinks':['cola','milk','water']
    
    #rendered.html
    {% filter upper %}
    {% for drink in drinks %}
    {{ drink }}
    {% endfor %}
    {% endfilter %}
    
  • {% with %}

    对于创建没有被view方法或者必须通过“高昂”的操作才能得到的变量,用该tag就会非常方便。

    #urls.py
    'drink_cost':2
    
    #rendered.html
    {% with drinktax=drink_cost drinkpro=drink_cost %}
    {{ drinktax}}<br>
    {{drinkpro}}
    {% endwith %}
    

Spacing and Special Characters

  • {% autoescape %}

    在{% autoescape on %}...{% endautoescape %}之间的将被转义:

    # urls.py
    'drink_cost':'<b>escape?</b>'
    
    # rendered.html
    {% autoescape on %}
    {{ drink_cost }}
    {% endautoescape %}
    
{% autoescape off %}
{{ drink_cost }}
{% endautoescape %}
  • {% spaceless %}...{% endspaceless %}

    仅仅移除tag之间的空隙。

  • {% templatetag %}

    用于输出组成template tag的特殊符号:

    Argument Outputs
    openblock {%
    closeblock %}
    openvariable {{
    closevariable }}
    openbrace {
    closebrace }
    opencomment {#
    closecomment #}
    #rendered.html
    {% templatetag openvariable %} url 'entry_list' {% templatetag closeblock %}
    
  • {% verbatim %}

    在{% verbatim %}...{% endverbatim %}之间的内容将被不被渲染。也可以在该tag中添加自定义的名字,即{% verbatim mytag %}...{% endverbatim %}

    # rendered.html
    {% verbatim myblock %}
        Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
    {% endverbatim myblock %}
    
  • {% lorem *}

    {% lorem [count] [method] [random] %}
    

    三个可选参数:

    Argument Description
    count A number (or variable) containing the number of paragraphs or words to generate (default is 1)
    method Either w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b).
    random The word random, which if given, does not use the common paragraph (“Lorem ipsum dolor sit amet…”) when generating text.
    # rendered.html
    {% lorem 3 p %}
    

    Template structures

  • {% block %}

  • {% comment %}...{% endcomment %}之间的将不被渲染

    # rendered.html
    <p>Rendered text with </p>
    {% comment  %}
        <p>Commented out text with {{ create_date|date:"c" }}</p>
    {% endcomment %}
    

  • { # #}:单独一行注释

    <p>Great feeling</p>
    {# This is comment  #}
    

  • {% extends %}

  • {% include %}

  • {% load %}

    URLs

  • {% url %}

##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
原文地址:https://www.cnblogs.com/johnyang/p/13624443.html