Jinja2 基本使用
前言
在 Flask 中渲染 HTML 通常交给模板引擎,Flask 默认配套的模板引擎是 Jinja2。Flask 默认会在当前目录下的 templates 文件夹中寻找模板文件。
HelloWorld
在 templates 文件夹下创建 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Flask 应用代码:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
如果想把模板文件放在其它目录,可以在创建 app 时指定路径:
app = Flask(__name__, template_folder="templates2")
渲染变量
将数据动态渲染到模板。这里通过查询参数把 fruit 传给模板:
from flask import request
@app.get("/temp/variable")
def temp_variable():
favourite_fruit = request.args.get("fruit")
return render_template("variable.html", favourite_fruit=favourite_fruit)
templates/variable.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>temp variable</title>
</head>
<body>
<h1>My favorite fruit is {{favourite_fruit}}</h1>
</body>
</html>
字典的值和对象的属性在模板中可以通过点号访问:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@app.get("/temp/var2")
def temp_var2():
name = request.args.get("name")
age = request.args.get("age")
return render_template("var2.html", user=User(name, age))
templates/var2.html:
<h1>My name is {{user.name}}, age is {{user.age}}</h1>
if 判断语句
{% if user %}
<h1>Hello {{ user.name }}!</h1>
{% elif guest %}
<h1>Hello Guest!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
Jinja2 中的 if 还支持 and / or / not、in、== 等表达式:
{% if user.age >= 18 and user.age < 60 %}
<p>成年</p>
{% endif %}
for 循环语句
<ul>
{% for item in items %}
<li>{{ loop.index }}: {{ item }}</li>
{% endfor %}
</ul>
loop 是 Jinja2 内置的循环对象,常用属性:
loop.index:当前迭代次数(从 1 开始)。loop.index0:当前迭代次数(从 0 开始)。loop.first/loop.last:是否第一个/最后一个。loop.revindex:倒数的迭代次数。
遍历字典:
{% for key, value in user.items() %}
<p>{{ key }}: {{ value }}</p>
{% endfor %}