Web 开发中, 在前后端不分离的模式状态下, 模板是最为重要的一部分, 我们可以将前端的页面放在 templates 目录下, 然后再视图函数中, 调用render_templates 函数, 将后端数据通过 key=value 的形式, 传递模板, 更能方便的处理数据。
模板基本使用:
在templates目录下创建一个watchlist.html作为模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{
{ user.username }}'s Watchlist</title>
</head>
<body>
<a href="{
{ url_for('index') }}">← Return</a>
<h2>{
{ user.username }}</h2>
{% if user.bio %}
<i>{
{ user.bio }}</i>
{% else %}
<i>This user has not provided a bio.</i>
{% endif %}
{# 下面是电影清单(这是注释) #}
<h5>{
{ user.username }}'s Watchlist ({
{ movies|length }}):</h5>
<ul>
{% for movie in movies %}
<li>{
{ movie.name }} - {
{ movie.year }}</li>
{% endfor %}
</ul>
</body>
</html>
有了模板, 自然要有一个视图函数去渲染它:
@app.route('/')
def movie_list():
user = {
'username': 'Grey Li',
'bio': 'A boy who loves movies and music.',
}
movies = [
{'name': 'My Neighbor Totoro', 'year': '1988'},
{'name': 'Three Colours trilogy', 'year': '1993'},
{'name': 'Forrest Gump', 'year': '1994'},
{'name': 'Perfect Blue', 'year': '1997'},
{'name': 'The Matrix', 'year': '1999'},
{'name': 'Memento', 'year': '2000'},
{'name': 'The Bucket list', 'year': '2007'},
{'name': 'Black Swan', 'year': '2010'},
{'name': 'Gone Girl', 'year': '2014'},
{'name': 'CoCo', 'year': '2017'},
]
return render_template('watchlist.html', user=user, movies=movies)
假如 user, movies 的数据是从数据库中查询出来的。
可以看到这里调用了 flask 提供的 render_template 方法, 然后将数据以 key=value 的形式传递到模板中, 就可以在模板中方便的处理渲染了
上下文:
模板上下文包含了很多变量,其中包括我们调用render_template()函数时手动传入的变量以及Flask默认传入的变量。
除了从视图函数中传递来的变量, 我们也可以在末班中定义变量, 使用 set 标签
{% set navigation = [('/', 'Home'), ('/about', 'About')] %}
也可以将一部分模板数据定义为变量,使用set和endset标签声明开始和结束:
{% set navigation %}
<li><a href="/">Home</a>
<li><