This article mainly introduces the Jinja2 template engine learning tutorial in the Python Flask framework. the usage of Jinja2 template engine is also an important knowledge in Flask Web development, for more information, see the template function of Flask. it 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/
')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:
Hello Sample{% if name %} Hello {{ name }} !{% else %} Hello World!{% endif %}
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' %} This is admin console{% elif name %} Welcome {{ name }}!{% else %} Please login{% endif %}
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' %} Helle admin{% elif name %} "Hello" ~ {{ name }} ~ "!"{% else %} Hello World!{% endif %} {% for digit in digits %} {{ digit }} {% endfor %}
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:
{% for user in users if not user.hidden %} {% if loop.first %}
User List:
{% endif %}
-
User No. {{ loop.index }}
-
{{ user.name }}
{% if loop.last %}
Total Users: {{ loop.length }}
{% endif %} {% else %}
No users found {% endfor %}
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 p element of the parity item has different classes. If we add the following CSS style, we can see the zebra crossing.
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/ ') 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 %}
{% for item in items %}
- {{ item }}
{% endfor %}
{% endraw %}
Automatic escape
Let's Change the Flask code "hello ()" method at the beginning of this article:
@app.route('/hello')@app.route('/hello/
')def hello(name=None): if name is None: name = '
World' return render_template('hello.html', name=name)
Access "#: 5000/hello". the page displays "Welcome ".World!", This is the HTML tag""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 %} Hello {{ name }}!{% endautoescape %}
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.
{{ request.url }}
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:
User: {{ session.user }}
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:
DB: {{ g.db }}
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.
Host: {{ config.DEBUG }}
"Config" is a global object and can be accessed without the request lifecycle.
Url_for () function
Hosts file.
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:
Current App is: {{ appname }}
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:
Current Time is: {{ current_time() }}
Current Day is: {{ current_time("%Y-%m-%d") }}
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:
Hello Sample
Hello World! Request URL: {{ request.url }}
User: {{ session.user }}
DB: {{ g.db }}
Host: {{ config.DEBUG }}
Current App is: {{ appname }}
Current Time is: {{ current_time() }}
Current Day is: {{ current_time("%Y-%m-%d") }}
{% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} Flash Message: {{ message }} {% endfor %} {% endif %}{% endwith %}
For more articles about the Jinja2 template engine in the Python Flask framework, refer to the PHP Chinese website!