Django template built-in tags

Source: Internet
Author: User

Django built-in tag Autoescape

Controls the behavior of the current auto-escape with on and off two options

 on%}    {{body}}{% endautoescape%}
Block

Defines a block that can be overridden by a child template in a template (previous section) with examples of use

Comment

Note, the contents between{% comment %} and {% endcomment %} are interpreted as comments

Crsf_token

A label that prevents CSRF attacks (cross-site request forgery)

Cycle

A string or variable given by a loop that can be mixed

{% for O in some_list%}     <  class= "{% cycle ' row1 ' rowvalue2 ' row3 '%}">        ...     </ TR > {% endfor%}

It is worth noting that the value of the variable here is not automatically escaped by default, either you believe your variable, or you are using a forced escape method,

{% for O in some_list%}     <  class= "{% filter force_escape%}{% cycle rowvalue1 rowvalue2%}{% endfilter%}">         ...     </ TR > {% endfor%}

In some cases, you might want to loop the next value of the outer reference loop, when you need to give the cycle a name that represents the current loop value, but you can use that variable in the cycle tag to get the next value of the loop.

<TR>    <TDclass= "{% cycle ' row1 ' row2 ' as rowcolors%}">...</TD>    <TDclass= "{{rowcolors}}">...</TD></TR><TR>    <TDclass= "{% cycle rowcolors%}">...</TD>    <TDclass= "{{rowcolors}}">...</TD></TR>

The result of the rendering is

<TR>    <TDclass= "Row1">...</TD>    <TDclass= "Row1">...</TD></TR><TR>    <TDclass= "Row2">...</TD>    <TDclass= "Row2">...</TD></TR>

But once the cycle label is defined, the default is to use the first value of the loop, when you just want to define a loop and not want to print the value of the loop (for example, if you define a variable in the parent template to facilitate inheritance), You can use the silent parameter of cycle (you must ensure that silent is the last parameter of cycle, and silent has inherited characteristics, although the cycle of the second row has no silent parameters, But since rowcoclors is defined earlier and contains silent parameters, the second cycle also features a silent loop.

Silent %}{% cycle rowcolors%}
Debug

Outputs all debugging information, including the current context and imported modules

Extends

Indicates that the current template inherits a parent template

Accept a variable or string constant that contains the name of the parent template

Filter

Filter content through the available filters, and the filters can also be mutually (called)

{% filter Force_escape|lower%}    This text would be html-escaped, and would appear in all lowercase. {% endfilter%}
Firstof

Returns the first available (not false) variable or string in the list, noting that the variable in Firstof is not automatically escaped

{% firstof var1 var2 var3 "fallback value"%}
For

For loop, you can add a reversed parameter to iterate through the list in reverse order

{% for obj in list reversed%

You can also write a for statement based on the data in the list, for example, for a dictionary type of data

{% for key, value in data.items%}    {{Key}}: {{value}}{% endfor%}

The For Loop also has a series of useful variables

variables Description
Forloop.counter Index of the current loop, starting from 1
Forloop.counter0 Index of the current loop, starting from 0
Forloop.revcounter Index of the current loop (from the back), starting with 1
Forloop.revcounter0 Index of the current loop (from the back), starting with 0
Forloop.first If this is the first time the loop returns True
Forloop.last If this is the last time the loop returns True
Forloop.parentloop If it is a nested loop, it refers to an outer layer of loops
For...empty

If the for loop parameter-list is empty, the contents of empty are executed

< ul > {% for athlete in athlete_list%}     < Li > {{Athlete.name}} </ Li > {% empty%}     < Li > Sorry, no athlete in this list! </ Li > {% endfor%} < ul >
If

Conditional statements

if athlete_list%}    elif athlete_in_locker_room_list%}    else %}    endif  %}
Boolean operator

And,or and not three Boolean operators can be used inside the IF tag

==,!=,<,>,<=,>=,in,not in equal operator

These operators are not described in detail, at a glance

In the IF tag, these operators can be made into complex expressions

Ifchange

Detects if a value has changed at the end of the loop

So this tag is actually used in the loop, there are two uses:

    • When the parameter is not accepted, the comparison is that the contents of the Ifchange tag are in effect when compared to the previous change.
    • When one or more parameters are accepted, if one or more parameters change, the change takes effect.

Ifchange can have else label

{% for match in matches%}     <  style= "Background-color:        {% ifchanged match.ballot_id%}            {% cycle"Red "blue "%}        {% Else%}            Grey        {% endifchanged%}    ">{{match}}</Div  >{% endfor%}
Ifequal

The contents of the output block can be combined with the else output only when the two parameters are equal

ifequal user.username "Adrian"%}    ... {% endifequal%}
Ifnotequal

Like Ifequal.

Include

Loads a template and renders it with the current context (the context of the template that is the template), accepting a variable or string argument

Of course you can also pass some parameters in the include

{% include "name_snippet.html" with person= "Jane" greeting= "Hello"%}

If you only want to accept arguments that are passed and do not accept the context of the current template, you can use the only parameter

{% include ' name_snippet.html ' with greeting= ' Hi ' only%}
Load

To load a custom template label collection, see a separate section explaining

Now

Display the current time date, accept the parameters of the formatted string

It is {% now "JS F Y h:i"%}

The

parameter has some reference parameters already defined: &NBSP;date_format (Month Day year datetime_format (month) SHORT_DATE_FORMAT (month/day/ year ) Span style= "line-height:1.5;" > or  short_datetime_format (month/day/year/time)

Regroup

To re-group similar objects of a list by a common attribute, join the list of cities you have in the following

Cities = [    {'name':'Mumbai','population':'19,000,000','Country':'India'},    {'name':'Calcutta','population':'15,000,000','Country':'India'},    {'name':'New York','population':'20,000,000','Country':'USA'},    {'name':'Chicago','population':'7,000,000','Country':'USA'},    {'name':'Tokyo','population':'33,000,000','Country':'Japan'},]

You want to follow the national country this property to re-group has obtained the following results, then you can do so

    • India
      • Mu mbai:19,000,000
      • calcutta:15,000,000
    • USA
      • New york:20,000,000
      • Chicago : 7,000,000
    • Japan
      • tokyo:33,000,000
 {% regroup  cities by country as country_list%   <ul>{% for  country in  country_list%}  <li>{{Country.grouper}}  <ul> {% for  item in  country.list%
   
    }  <li>{{Item.name}}: {{item.population}}</li>
     {% endfor%  </ul> </li>{% E Ndfor% </ul> 
   

It is important to note that regroup is not reordered, so make sure that city is ordered by country before regroup, otherwise you will not get the results you expect, if you are unsure you can sort by Dictsort filter

{% regroup Cities|dictsort:"country" by country as country_list%}
Spaceless

Remove spaces between HTML tags, note spaces between labels, and spaces between labels and content are not deleted

{% spaceless%}     <p>        <a href="foo/">Foo</a>    </p>{% Endspaceless%}

The result is

<p><a href="foo/">Foo</a></p>
Ssi

Output the contents of a given file on a page

{% ssi/home/html/ljworld.com/includes/right_generic.html%}

Use the parsed parameter to make the input content available as a template so that the context of the current template can be used

parsed %}
Url

Returns a reference to an absolute path (a URL without a domain name), the first parameter to accept is the name of a view function, and then the URL of the view function is found from the URLs configuration file.

WidthRatio

This tag calculates the ratio of the given value to the maximum value, and then multiplies the ratio by a constant, returning the final result

<src= "Bar.gif"  height= "Ten"  width= "{% WidthRatio This_value Max_value} "/>
With

Cache complex variable names with simpler variable names

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

Although the original intention is this, but you do not have to be so, haha

{% with alpha=1 beta=2%}    ... {% Endwith%}

Django built-in tags it's over for everyone, haha.

P

Django template built-in tags

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.