Jinja2 template engine learning tutorial in the Flask framework of Python, flaskjinja2

Source: Internet
Author: User

Jinja2 template engine learning tutorial in the Flask framework of Python, flaskjinja2

The Flask template function is implemented based on the Jinja2 template engine. The template file is stored in the current subdirectory templates (this name must be used.
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 template expressions are included in the separator "{{}}"; the control statements are included in the separator "{%%}". In addition, the template supports annotations, all are contained in the separator "{##}" and block annotations are supported.
Expression

There are several expressions:

  • The most common variable is that it is passed by the Flask rendering template, for example, the "name" in the previous example"
  • It can also be any basic Python type, such as string {"Hello"}, enclosed in quotation marks; or value, list, ancestor, Dictionary, Boolean value. Directly displaying the basic type is meaningless. It is generally used together with other expressions.
  • Operation. Including arithmetic operations, such as {2 + 3 }}; comparison operations, such as {2> 1 }}; logical operations, such as {False and True }}
  • Filter "|" and tester "is ". This will be introduced later
  • Function call, such as {current_time () }}; array subscript operation, such as {arr [1]}
  • "In" operator, such as {1 in [1, 2, 3]}
  • String connector "~", Similar to "+" in Python, such as {"Hello "~ Name ~ "!" }}
  • "If" keyword, for example, {'Hi, % s' % name if name }}. The "if" here is not a condition control statement.

Control statement

The control statement of Jinja2 is mainly the condition control statement if, and the loop control statement for. The syntax is similar to Python. We can modify the template code in the previous section:

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

The above is an example of a condition control statement. Note that if control statements should end with "{% endif %. In a template, indentation cannot be used to determine the end of a code block. Let's take a look at the example of a loop. First, let's change the "hello" function in the Python code and let it upload two lists to 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' %}  

Like the if statement, the for control statement must end with "{% endfor %. On the page, there is a space between each element. If you do not want a space, it must be at the end of the "for" statement, and the "endfor" statement are preceded by a "-" sign. For example:

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

You can see that the number "12345" is displayed together. Let's take a look at a complex loop example:

<dl>  {% for user in users if not user.hidden %}  {% if loop.first %}  <div>User List:</div>  {% endif %}  <div class="{{ loop.cycle('odd', 'even') }}">  <dt>User No. {{ loop.index }}</dt>  <dd>{{ user.name }}</dd>  </div>  {% if loop.last %}  <dir>Total Users: {{ loop.length }}</dir>  {% endif %}  {% else %}  <li>No users found</li>  {% endfor %}</dl>

There are three knowledge points here. First, the for loop supports else statements. When the list "users" to be traversed is null or None, the else statement is entered.
Second, use the if keyword after the for statement to filter items in the loop. In this example, all users whose hidden attribute is True are filtered out.
In addition, the built-in variables of Jinja2 can be accessed in the for loop. In this example, we will display the title before the first item, the total number after the last item, and the serial number for each item. In addition, the HTML div element of the parity item has different classes. If we add the following CSS style, we can see the zebra crossing.

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

The built-in cycle variables of Jinja2 mainly include the following:

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 "jinja2.ext. loopcontrols "extension, you can also use" {% break %} "and" {% continue %} "in the loop to control loop execution.
Other common statements:

Ignore template syntax

Sometimes, we want to display symbols like "{{}}" on the page. What should we do? Jinja2 provides the "raw" statement to ignore all template syntaxes.

{% raw %}  <ul>  {% for item in items %}    <li>{{ item }}</li>  {% endfor %}  </ul>{% endraw %}

Automatic escape

Let's 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)

Access "http: // localhost: 5000/hello". The page displays "Welcome <em> World </em> !", That is, the HTML Tag "<em>" is automatically escaped. Flaskwill enable HTML format automatic escape for template files of the following types: ".html, ".htm,. xml, and ".xhtml. This also prevents HTML syntax injection. What if we don't want to be escaped?

{% autoescape false %} 

Set "autoescape" to "false". Otherwise, set "true" to enable automatic escape. Enable the jinja2.ext. autoescape extension before using the autoescape switch. In the Flask framework, this extension is enabled by default.
Assignment

Assign a value to the 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 in the with statement block:

{% with foo = 1 %}  {% set bar = 2 %}  {{ foo + bar }}{% endwith %}{# foo and bar are not visible here #}

Enable the "jinja2.ext. with _" extension before using the "with" keyword. In the Flask framework, this extension is enabled by default.
Execution expression

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

Looking at the code above, we want to execute the "append" Operation in the list, and then use "{arr. the append ('rainy')} page outputs "None" and changes it to "{%}" for execution. The program reports an error because this is an expression and is not a statement. What should we do? 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 %}

Context
Each Flask Request has a lifecycle, and the Request has its Context. As a template rendered in a request, it is also within the request lifecycle. Therefore, templates in the Flask application can use the environment variables in the request context and some auxiliary functions. This article will introduce these variables and functions.
Standard context variables and functions

Request object
The request object can be used to obtain the request method "request. method", form "request. form", request parameter "request. args", and request address "request. url. It is a dictionary. In the template, you can obtain the content as long as it is enclosed by the expression symbol.

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

This object is unavailable in an environment with no request context.
Session object session
The session object can be used to obtain the State saved in the current session. It is a dictionary. In the template, you can use the expression symbol "{{}}" to obtain this object.
The Flask code is as follows. Do not forget to set the session key:

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

Template code:

<p>User: {{ session.user }}</p>

This object is unavailable in an environment with no request context.
Global Object g
Global variable g, used to save the global Content Used in the request, such as database connection. The template is also accessible.
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 application context and is valid only for one request lifecycle. In an environment without application context, this object is unavailable.
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 and can be accessed without the request lifecycle.
Url_for () function
Hosts file.

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

This function is global and can be called without the request lifecycle.
Get_flashed_messages () function
The get_flashed_messages () function is used to obtain message flashes. This is also a global function.
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. Next we will first define a context variable. 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 an appname attribute. The value is the name of the current application. We have introduced that the "current_app" object here is a proxy defined in the application context. Use "@ app. context_processor is a context processor that runs the modified function before the template is rendered and imports the dictionary returned by the function into the template context, merge with template context. Then, the "appname" in the template is like the "request" and "session" introduced in the preceding section, and becomes an accessible context object. We can output it in the template:

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

Custom Functions
Similarly, we can customize the context function. We only need to point the attribute of the dictionary returned in the previous example to a function. Next we will 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 the template:

<p>Current Time is: {{ current_time() }}</p> <p>Current Day is: {{ current_time("%Y-%m-%d") }}</p>

The context processor can modify multiple functions, that is, we can define multiple context variables and functions.
Complete instance:
Flask code:

from flask import Flask, render_template, session, g, current_appimport time app = Flask(__name__) @app.route('/')def index():  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.