The JINJA2 template engine in the flask framework of Python

Source: Internet
Author: User
The template functionality of flask is implemented based on the JINJA2 template engine. The template file is stored under current subdirectory templates (be sure to use this name).

The main.py code is as follows:

From flask import flask, render_template app = Flask (__name__) @app. Route ('/hello ') @app. Route ('/hello/<name> ') def hello (name=none):  return render_template (' hello.html ', name=name)  if __name__ = = ' __main__ ':  app.run (debug=true)

The hello.html code is as follows:

<! DOCTYPE html>

The expression of the template is contained within the delimiter "{{}}"; The control statement is included in the delimiter "{%%}"; In addition, the template also supports annotations, which are contained within the delimiter "{# #}" and support block annotations.
An expression

There are generally several types of expressions:

    • The most common is the variable, which is passed when the template is rendered by flask, such as "name" in the previous example

    • It can also be any of the Python base types, such as the string {{' Hello '}}, enclosed in quotation marks, or a value, list, meta-ancestor, dictionary, Boolean. Direct display of the underlying type does not make sense, generally with other expressions

    • Operation. Include arithmetic operations, such as {{2 + 3}}; Comparison operations, such as {{2 > 1}}; Logical operations, such as {{False and True}}

    • Filter "|" And the tester "is". This will be introduced in the back.

    • function call, such as {{Current_time ()}}; array subscript operation, such as {{arr[1]}}

    • "In" operator, such as {{1 in [[+]}}

    • The string connector "~" acts as "+" in Python, such as {{"Hello" ~ Name ~ "!"}}

    • "If" keyword, such as {{' Hi,%s '% name if name}}. The "if" here is not a conditional control statement.

Control statements

JINJA2 control statements are mainly conditional control statements if, and loop control statements for, syntax similar to Python. We can change the template code in the next section:

{% if name and name = = ' admin '%}  

Above is an example of a conditional control statement, noting that the if control statement ends with "{% endif%}". The template cannot be indented in the same way as in code to determine the end of a block of code. To take a look at the example of a loop, let's change the "Hello" function in the Python code to pass two lists into the template.

def hello (name=none):  return render_template (' hello.html ', Name=name, digits=[1,2,3,4,5],              users=[{' name ': ' John '},                 {' name ': ' Tom ', ' Hidden ': True},                 {' name ': ' Lisa '}                 {' name ': ' Bob '}]

The template is as follows:

{% if name and name = = ' admin '%}  

As with the IF statement, the for control statement ends with "{% endfor%}". On the page, there will be spaces between each element, and if you do not want a space, you should add a "-" to the end of the "for" statement, and to the "endfor" statement. Such as:

{% for digit in digits-%}  {{digit}} {%-ENDfor%}

You can see the numbers "12345″ are shown together." Let's look at a complex loop example:

<dl>  {% for user in users if not User.hidden%}  {% if Loop.first%}  <p>user list:</p>  {% endif%}  <p class= "{{loop.cycle (' odd ', ' even ')}" >  <dt>user No. {{Loop.index}}</dt>  & lt;dd>{{user.name}}</dd>  </p>  {% if loop.last%}  <dir>total Users: {{loop.length}} </dir>  {% endif%}  {% Else%}  <li>no users found</li>  {% endfor%}</dl>

Here are three points of knowledge. The For loop first supports the Else statement, and when the list "users" to be traversed is empty or none, the Else statement is entered.
Second, you can filter the items in the loop by using the IF keyword after the for statement. In this case, all the user with the hidden attribute true will be filtered out.
In addition, the JINJA2 loop built-in variable can be accessed in the For loop. In this case, we'll show the title before the first item, the total number after the last item, and each item showing the number. In addition, the HTML P element of the parity item will have a different class. If we add the following CSS style, we can see the zebra crossing.

<style type= "Text/css" >  . Odd {    background-color: #BDF;  } </style>

JINJA2 's cyclic built-in variables are mainly as follows:


1

2

3

4

5

6

7

8

9

10

11

12


from flask import flask , render_template

app = Flask(__name__)

@ app . Route ('/hello ')

@ app . Route ('/hello/<name> ')

def Hello(name=None):

return render_template(' hello.html ', name = name )

if __name__ = = ' __main__ ':

app. Run (debug=True)


In addition, if you enable the "jinja2.ext.loopcontrols" extension, you can also use "{% break%}" and "{% continue%}" in loops to control loop execution.
Other common statements:

Ignore template syntax

Sometimes, we are on the page to show the "{{}}" symbols such as what to do? JINJA2 provides a "raw" statement to ignore all template syntax.

{% RAW%}  <ul>  {% for item in items%}    <li>{{item}}</li>  {% endfor%}  </ul>{% Endraw %}

Auto Escape

We will change the flask code "Hello ()" method at the beginning of this article:

@app. Route ('/hello ') @app. Route ('/hello/<name> ') def hello (name=none):  If Name is None:    name = ' <em >World</em> '  return render_template (' hello.html ', name=name)

At this point, access "Http://www.php.cn/:5000/hello", the page will show "Welcome <em>world</em>!", that is, the HTML tag "<em>" is automatically escaped. Flask will automatically escape the HTML format for ". html", ". htm", ". xml", ". xHTML", which are four types of template files. This can also prevent HTML syntax injection. What if we don't want to be escaped?

{% Autoescape false%} 

Set the "autoescape" switch to "false" and, conversely, set "true" to turn on auto-escaping. To enable the "jinja2.ext.autoescape" extension before using the "autoescape" switch, this extension is enabled by default in the Flask framework.
Assign value

Assign a value to a variable using the "Set" keyword:

{% Set items = [[1,2],[3,4,5]]%}

With statement

Similar to the "with" keyword in python, it can limit the scope of objects within a with statement block:

{% with foo = 1}  {% Set bar = 2}  {{foo + bar}} {% Endwith%} {# Foo and bar is not visible here #}

To enable the "jinja2.ext.with_" extension before using the "with" keyword, this extension is enabled by default in the Flask framework.
Executing an expression

{% with arr = [' Sunny ']%} {{arr.append (' Rainy ')}} {{arr}} {% Endwith%}

Look at the above code, we want to perform the "append" operation of the list, when the "{{arr.append (' Rainy ')}}" page will output "None", and replace with "{%}" to execute, the program will error, because this is an expression, not a statement. So what? We can enable the "jinja2.ext.do" extension. Then execute the "Do" statement in the template:

{% with arr = [' Sunny ']%} {% do arr.append (' Rainy ')%} {{arr}} {% Endwith%}

Contextual environment
Flask Each request has a life cycle, and in its lifecycle requests that it have its contextual request context. As a template rendered in a request, nature is also within the life cycle of the request, so templates in the Flask application can use environment variables in the context of the request, as well as some auxiliary functions. These variables and functions are described in this article.
Standard context variables and functions

Requesting object request
The request object can be used to obtain the requested method "Request.method", the form "Request.Form", the requested parameter "Request.args", the request Address "request.url" and so on. It is itself a dictionary. In the template, you can get the same content, as long as the expression symbol "{{}}" is enclosed.

<p>{{Request.url}}</p>

In an environment without a request context, this object is not available.
Sessions Object session
The session object can be used to get the state saved in the current session, which is itself a dictionary. In the template, you can get this object by using the expression symbol "{{}}".
Flask code below, don't forget to set the session key OH:

@app. Route ('/') def index ():  session[' user '] = ' guest '  return render_template (' hello.html ') App.secret_key = ' 123456 '

Template code:

<p>user: {{Session.user}}</p>

In an environment without a request context, this object is not available.
Global Object G
Global variable g, which is used to save the request with global content, such as a database connection. can also be accessed in the template.
Flask Code:

@app. Route ('/') def index ():  g.db = ' mysql '  return render_template (' hello.html ')

Template code:

<p>db: {{g.db}}</p>

The G object is stored in the context of the application and is only valid for the lifetime of a request. In an environment where there is no application context, this object is not available.
Flask Configuration Object Config
The imported configuration information is saved in the "app. Config" object. This configuration object can also be accessed in the template.

<p>host: {{config. DEBUG}}</p>

"Config" is a global object that can be accessed from the request life cycle.
Url_for () function
The Url_for () function can be used to quickly acquire and build url,flask and also introduce this function into the template, such as the following code, to get the "style.css" file in the static directory.

<link rel= "stylesheet" href= "{{url_for (' static ', filename= ' Style.css ')}}" >

The function is global and can be called away from the request life cycle.
Get_flashed_messages () function
The Get_flashed_messages () function is used to get the message to flash. This is also a function that can be used globally.
Custom Context variables and functions

Custom variables
In addition to the standard context variables and functions provided by flask, we can also define them ourselves. Let's start by defining a context variable, and in the Flask application code, add the following function:

From flask import Current_app @app. Context_processordef appinfo ():  return Dict (appname=current_app.name)

The function returns a dictionary with a property "appname" and a value of the name of the current app. As we have described, the "Current_app" Object here is a proxy defined in the context of the application. The function is decorated with the "@app. Context_processor" Adorner, which is a context handler that runs the functions it modifies before the template is rendered, and imports the dictionary returned by the function into the template context, merging with the template context. Then, in the template "appname" as described in the previous section of the "request", "session" as an accessible context object. We can output it in a template:

<p>current App is: {{appname}}</p>

Custom functions
In the same vein, we can customize the context function by pointing to a function that returns the dictionary in the example above, and then we define a context function to get the current time of the system:

Import time @app. Context_processordef get_current_time ():  def get_time (timeformat= "%b%d,%Y-%h:%m:%s"):    Return Time.strftime (TimeFormat)  return Dict (current_time=get_time)

We can try to output it in a template:

<p>current time is: {{current_time ()}}</p> <p>current: {{current_time ("%y-%m-%d")}}</p >

The context processor can decorate multiple functions, that is, we can define multiple context variables and functions.
Complete Example:
Flask Code:

From flask import Flask, render_template, Session, G, current_appimport time app = Flask (__name__) @app. Route ('/') def Inde X ():  session[' user '] = ' guest '  g.db = ' mysql '  return render_template (' hello-2.html ') @app. Context_ Processordef appinfo ():  return Dict (appname=current_app.name) @app. Context_processordef get_current_time ():  def get_time (timeformat= "%b%d,%Y-%h:%m:%s"):    return Time.strftime (TimeFormat)  return Dict (current_ Time=get_time) App.secret_key = ' 123456 ' if __name__ = = ' __main__ ':  app.run (debug=true)

Template code:

<!doctype Html><title>hello sample</title><link rel= "stylesheet" href= "{{url_for (' static ', Filename= ' Style.css ')}} "> 


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.