"Flask" Jinja2 template language

Source: Internet
Author: User
Tags iterable

Jinja2

JINJA2 is the mainstream template language in Python Web programming. Because Flask is based on the development of JINJA2 and Werkzeug, in the installation of Flask JINJA2 automatically installed on it.

There are a lot of ways to use JINJA2, and the following will supplement or explain in more detail the use of Jinja2 as a template language.

"JINJA2 Official Document" http://docs.jinkan.org/docs/jinja2/

Basic semantics

See the example of the previous template to know that Jinja2 to make the template file, the text content can be broadly divided into several categories. For example, special text (not escaped, such as text in html,xml format), variable represented by {{}}, or macro call, {%} represents logical control, {# #} represents a comment, where content is not escaped by the template engine.

Set Statement Assignment value

In all previous examples, the value of the variable in the template appears to have only one source, which is the supply from the backend. But actually we can assign the variable at the template level, which is the form of {% set variable_name= "value"%}. This gives the template the ability to assign variables internally, which increases flexibility.

Filter filters

JINJA2 can use filters to perform two processing of first-hand data on incoming templates. The filter is in the form of a pipe symbol to connect first-hand data and two data processing methods. For example, write in the template:

{{My_variable|default ("my_variable is not Defined")}}

This means that the first-hand data here is the value of the variable passed by the backend my_variable. If the variable is not defined, then there is a default filter method that specifies what should be displayed when it is not defined. There are a lot of filter methods, and a variety of filter methods allow data to be transferred from the backend to the front and then be flexible, thus improving the convenience and agility of the entire programming. Other commonly used or I look at the more useful filter methods are:

The first parameter in the following description refers to the value passed through the pipe, and the method parameter that is actually written on the right side of the pipe should be less than the one shown in the following description, like the self parameter in Python object-oriented Programming * * * *

attr (object,name) such as account|attr ("name") in the account is expected to be a dictionary (or according to JS is an object), this place is the value of the real account[' name ']

Capitalize (s) capitalize the first letter of the string, followed by all lowercase

Default (Value,default_value=u ', boolean=false) sets defaults, and if no value is given, then the value of Default_value (that is, an empty string)

Filesizeformat (Value,binary=false) accepts a value and then translates it into an easy-to-read byte form such as 1.3mb,305byte, such as {{Size|filesizeformat ()}}

Float (value,default=0) accepts a value and converts it to float type

Escape (String) to invert HTML special characters such as <,>,& in a string to express HTML

GroupBy (Value,attribute) groups the collection of (a list of dictionaries) by the specified common attributes, returning a list of dictionaries. Each dictionary in this list has two items, the first key is grouper and then value is the value of the key in the original dictionary, which is based on the groupby distinction. Said a bunch of himself dizzy, below give an example.

For example, the template looks like this:

    <ul>        {% for group in Persons|groupby (' Gender ')%}            <li>{{group.grouper}}<ul>            {% for Person in group.list%}                <li>{{Person.first_name}} {{Person.last_name}}</li>            {% endfor%}</ul& gt;</li>        {% endfor%}    </ul>

And as the persons incoming data lst is this way:

LST =[] Lst.append ({"Gender":"male","first_name":"Frank","last_name":"Takanashi"}) lst.append ({"Gender":"female","first_name":"Bob","last_name":"Kazuya"}) lst.append ({"Gender":"female","first_name":"Ocean","last_name":"King"})

Then the final rendering of the finished file is as long as it looks like:

<ul>     <Li>female<ul>          <Li>Bob Kazuya</Li>           <Li>Ocean King</Li>        </ul>      </Li>      <Li>male<ul>          <Li>Frank Takanashi</Li>        </ul>       </Li></ul>

Int (Value,default) converts the value to an int type

Join (Value,sep=u ') takes an object of a sequence type, and then joins all sequence elements together as a string by the characters specified by Sep. Sep default is an empty string

Last/first/random (SEQ) returns the last/most front/random element of a sequence

Replace (String,old,new,count=none) takes a string, converts all of its old parts to new, replaces count times from left to right, and if you do not specify that count is the only one that replaces the first scan to

Reverse (value) accepts an iterator that iterates over an object and then returns its inverse sequence

Sort (value,reverse=false,case_sensative=false,attribute=none) sorts objects that can be iterated, sorted by default in ascending case insensitive.

Striptags (value) removes a tag from a piece of text, such as an XML format

SUM (iterable,attribute=none,start=0) sums the objects that can be iterated, and if you need to sum the values of a particular property, you can set the attribute property

Title (string) converts a string to a caption format display

Trim (value) removes all spaces at the beginning and end, equivalent to strip ()

Truncate (s,length=255,killwords=false,end= ' ... ') This is a more interesting way to convert a string into a shorthand form, such as "foo Bar" |truncate (5) can get Foo ..., if " Foo bar "|truncate (5,true) can get foo b ...

Round (value,precision=0,method= ' common ') rounds the numbers, and precision represents a few digits after the decimal point.

WordCount (s) calculates the number of words in a string

  

The above is not all of the filter methods, in general, these processing can be done in Python, Python can do very well, but it is bound to pass a lot of variables in the template. If you can do some two processing of these data at the template level, you can make the interaction between the backend and the front end small and improve the convenience of programming.

Logical Structure

JINJA2 and general programming languages, you can have if/else,for,is and so on as a logical control node. These keywords must be placed in {%} or {}}.

is keyword judging condition

Use the IS keyword and the so-called "test method" to obtain a Boolean value that can be used to make some logical judgments. For example {{name is defined}} can return true/false to reflect whether the variable name is defined. Similar "test methods" also include:

Callable (object) checks whether an object can be called

Defined/undefined (object) checks whether an object is/is defined

Divisibleby (value,num) checks if value can be divisible by digital num

Escaped (value) checks if an object has been transcoded

Iterable (value) checks whether an object is iterative

Lower/upper (value) checks whether an object is small/uppercase

None (value) checks if an object is None

Number (value) checks whether an object is a numeric

Sameas (Value,other) checks if an object is the same object as the other object

Usage: {% if Loop.index is Divisibleby (3)%} means that if the value of Loop.index can be divisible by 3, it will enter this logical branch.

Judgment statement

The judgment statement has nothing to say, anyway, {% if ...%}{% elif ...%}{% else%}{% endif%} format.

Looping statements

Loops in JINJA2 can only be through a for statement and do not have loop control functions such as break,continue. But within the scope of the For loop, you can access some of the properties of the special object loop to get some information about the loop. Loop has the following properties:

Loop.index Number of current loop iterations (counting from 1)

loop.index0 number of loop iterations starting from 0

Loop.revindex the number of iterations that need to be iterated until the end of the loop

Whether the Loop.first is the first iteration

Whether the loop.last is the last iteration

Number of items in the loop.length sequence

Loop.cycle auxiliary function for value in a series of sequences

For example, the following use case for this code:

{% for user in users%}   < Li >
{% if not loop.first%} {{user.username}} {% endif%}   </li >{% endfor%}

That is, if it is the first one in the loop, it does not show its username.

Template inheritance

Previously in the introduction also said several times, jinja2 template can be inherited. Takes the form of the keyword {% extends "parent.html"%}.

The parent template can have more than {% block xxx%}{% endblock%}, which can be specified to modify the contents of a block by {% block xxx%} in the child template. More detailed content is written in the general introduction of flask, will not repeat.

  

"Flask" Jinja2 template language

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.