Home > Article > Backend Development > Jinja2 template engine in Python’s Flask framework
Flask's template function is based on the Jinja2 template engine. Template files are stored in the current subdirectory templates (be sure to use this name).
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)
hello.html code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello Sample</title> </head> <body> {% if name %} <h1>Hello {{ name }} !</h1> {% else %} <h1>Hello World!</h1> {% endif %} </body> </html>
The template expressions are all included in the delimiter "{{ }}"; the control statements are all included in the delimiter "{% %}"; in addition, the template also supports Comments are included in the delimiter "{# #}", and block comments are supported.
Expression
There are generally several types of expressions:
The most commonly used ones are variables, which are passed when Flask renders the template. , for example, "name"
in the above example can also be any basic Python type, such as a string {{ "Hello" }}, enclosed in quotation marks; or a numerical value, List, tuple, dictionary, boolean. It makes no sense to directly display the basic type. Generally, the
operation is used in conjunction with other expressions. Including arithmetic operations, such as {{ 2 + 3 }}; comparison operations, such as {{ 2 > 1 }}; logical operations, such as {{ False and True }}
Filtering The tester "|" and the tester "is". This will be introduced later
Function calls, such as {{ current_time() }}; array subscript operations, such as {{ arr[1] }}
"in" operator, such as {{ 1 in [1,2,3] }}
Control statements
The control statements of Jinja2 are mainly the conditional control statement if and the loop control statement for. The syntax is similar to Python. We can change the template code in the previous section:{% if name and name == 'admin' %} <h1>This is admin console</h1> {% elif name %} <h1>Welcome {{ name }}!</h1> {% else %} <h1>Please login</h1> {% endif %}The above is an example of a conditional control statement. Note that the if control statement must use "{% endif %} " to end. In the template, you cannot rely on indentation to determine the end of the code block like you can in the code. Let's look at a loop example again. Let's first change the "hello" function in the Python code and let it 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' %} <h1>Helle admin</h1> {% elif name %} <h1>"Hello" ~ {{ name }} ~ "!"</h1> {% else %} <h1>Hello World!</h1> {% endif %} {% for digit in digits %} {{ digit }} {% endfor %}Same as the if statement, the for control statement must End with "{% endfor %}". On the page, there will be spaces between each element. If you don't want spaces, add a "-" sign at the end of the "for" statement and at the beginning of the "endfor" statement. For example:
{% for digit in digits -%} {{ digit }} {%- endfor %}You can see that the number "12345" is displayed together. Let’s look at a complex loop example again:
<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> <dd>{{ user.name }}</dd> </p> {% 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 the else statement. When the list "users" to be traversed is empty or None, the else statement is entered.
Secondly, use the if keyword after the for statement to filter the items in the loop. In this example, all users whose hidden attribute is True will be filtered out.
In addition, Jinja2’s built-in loop variables 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 elements for odd and even items will have 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 loop built-in variables of Jinja2 mainly include the following:
|
from flask import Flask, render_template app = Flask(__name__) @app.route('/hello') @app.route('/hello/8a11bc632ea32a57b3e3693c7987c420') def hello(name=None): return render_template('hello.html', name=name)
if __name__ == '__main__': app.run(debug=True) |
另外,如果你启用了”jinja2.ext.loopcontrols”扩展的话,你还可以在循环中使用”{% break %}”和”{% continue %}”来控制循环执行。
其它常用语句:
忽略模板语法
有时候,我们在页面上就是要显示”{{ }}”这样的符号怎么办?Jinja2提供了”raw”语句来忽略所有模板语法。
{% raw %} <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> {% endraw %}
自动转义
我们将本文一开始的Flask代码”hello()”方法改动下:
@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)
此时,访问”//m.sbmmt.com/:5000/hello”,页面上会显示”Welcome 907fae80ddef53131f3292ee4f81644bWorldd1c6776b927dc33c5d9114750b586338!”,也就是这个HTML标签”907fae80ddef53131f3292ee4f81644b”被自动转义了。Flask会对”.html”, “.htm”, “.xml”, “.xhtml”这四种类型的模板文件开启HTML格式自动转义。这样也可以防止HTML语法注入。如果我们不想被转义怎么办?
{% autoescape false %} <h1>Hello {{ name }}!</h1> {% endautoescape %}
将”autoescape”开关设为”false”即可,反之,设为”true”即开启自动转义。使用”autoescape”开关前要启用”jinja2.ext.autoescape”扩展,在Flask框架中,这个扩展默认已启用。
赋值
使用”set”关键字给变量赋值:
{% set items = [[1,2],[3,4,5]] %}
with语句
类似于Python中的”with”关键字,它可以限制with语句块内对象的作用域:
{% with foo = 1 %} {% set bar = 2 %} {{ foo + bar }} {% endwith %} {# foo and bar are not visible here #}
使用”with”关键字前要启用”jinja2.ext.with_”扩展,在Flask框架中,这个扩展默认已启用。
执行表达式
{% with arr = ['Sunny'] %} {{ arr.append('Rainy') }} {{ arr }} {% endwith %}
看上面这段代码,我们想执行列表的”append”操作,这时使用”{{ arr.append(‘Rainy') }}”页面会输出”None”,换成”{% %}”来执行,程序会报错,因为这是个表达式,不是语句。那怎么办?我们可以启用”jinja2.ext.do”扩展。然后在模板中执行”do”语句即可:
{% with arr = ['Sunny'] %} {% do arr.append('Rainy') %} {{ arr }} {% endwith %}
上下文环境
Flask每个请求都有生命周期,在生命周期内请求有其上下文环境Request Context。作为在请求中渲染的模板,自然也在请求的生命周期内,所以Flask应用中的模板可以使用到请求上下文中的环境变量,及一些辅助函数。本文就会介绍下这些变量和函数。
标准上下文变量和函数
请求对象request
request对象可以用来获取请求的方法”request.method”,表单”request.form”,请求的参数”request.args”,请求地址”request.url”等。它本身是一个字典。在模板中,你一样可以获取这些内容,只要用表达式符号”{{ }}”括起来即可。
<p>{{ request.url }}</p>
在没有请求上下文的环境中,这个对象不可用。
会话对象session
session对象可以用来获取当前会话中保存的状态,它本身是一个字典。在模板中,你可以用表达式符号”{{ }}”来获取这个对象。
Flask代码如下,别忘了设置会话密钥哦:
@app.route('/') def index(): session['user'] = 'guest' return render_template('hello.html') app.secret_key = '123456'
模板代码:
<p>User: {{ session.user }}</p>
在没有请求上下文的环境中,这个对象不可用。
全局对象g
全局变量g,用来保存请求中会用到全局内容,比如数据库连接。模板中也可以访问。
Flask代码:
@app.route('/') def index(): g.db = 'mysql' return render_template('hello.html')
模板代码:
<p>DB: {{ g.db }}</p>
g对象是保存在应用上下文环境中的,也只在一个请求生命周期内有效。在没有应用上下文的环境中,这个对象不可用。
Flask配置对象config
导入的配置信息,就保存在”app.config”对象中。这个配置对象在模板中也可以访问。
<p>Host: {{ config.DEBUG }}</p>
“config”是全局对象,离开了请求生命周期也可以访问。
url_for()函数
url_for()函数可以用来快速获取及构建URL,Flask也将此函数引入到了模板中,比如下面的代码,就可以获取静态目录下的”style.css”文件。
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
该函数是全局的,离开了请求生命周期也可以调用。
get_flashed_messages()函数
get_flashed_messages()函数是用来获取消息闪现的。这也是一个全局可使用的函数。
自定义上下文变量和函数
自定义变量
除了Flask提供的标准上下文变量和函数,我们还可以自己定义。下面我们就来先定义一个上下文变量,在Flask应用代码中,加入下面的函数:
from flask import current_app @app.context_processor def appinfo(): return dict(appname=current_app.name)
函数返回的是一个字典,里面有一个属性”appname”,值为当前应用的名称。我们曾经介绍过,这里的”current_app”对象是一个定义在应用上下文中的代理。函数用”@app.context_processor”装饰器修饰,它是一个上下文处理器,它的作用是在模板被渲染前运行其所修饰的函数,并将函数返回的字典导入到模板上下文环境中,与模板上下文合并。然后,在模板中”appname”就如同上节介绍的”request”, “session”一样,成为了可访问的上下文对象。我们可以在模板中将其输出:
<p>Current App is: {{ appname }}</p>
自定义函数
同理我们可以自定义上下文函数,只需将上例中返回字典的属性指向一个函数即可,下面我们就来定义一个上下文函数来获取系统当前时间:
import time @app.context_processor def get_current_time(): def get_time(timeFormat="%b %d, %Y - %H:%M:%S"): return time.strftime(timeFormat) return dict(current_time=get_time)
我们可以试下在模板中将其输出:
<p>Current Time is: {{ current_time() }}</p> <p>Current Day is: {{ current_time("%Y-%m-%d") }}</p>
上下文处理器可以修饰多个函数,也就是我们可以定义多个上下文环境变量和函数。
完整实例:
flask代码:
from flask import Flask, render_template, session, g, current_app import time app = Flask(__name__) @app.route('/') def index(): session['user'] = 'guest' g.db = 'mysql' return render_template('hello-2.html') @app.context_processor def appinfo(): return dict(appname=current_app.name) @app.context_processor def 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)
模板代码:
Hello Sample <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">Hello World!
Request URL: {{ request.url }}
<p>User: {{ session.user }}</p> <p>DB: {{ g.db }}</p> <p>Host: {{ config.DEBUG }}</p> <p>Current App is: {{ appname }}</p> <p>Current Time is: {{ current_time() }}</p> <p>Current Day is: {{ current_time("%Y-%m-%d") }}</p> {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} Flash Message: {{ message }} {% endfor %} {% endif %} {% endwith %}
更多Python的Flask框架中的Jinja2模板引擎相关文章请关注PHP中文网!