Jinja2 的语法和 Python 大致相同,你在后面会陆续接触到一些常见的用法。在模 板里,你需要添加特定的定界符将 Jinja2 语句和变量标记出来,下面是三种常用的 定界符:
* {{ ... }} 用来标记变量。
* {% ... %} 用来标记语句,比如 if 语句,for 语句等。
* {# ... #} 用来写注释。

案例

  • app.py的内容如下
from flask import Flask, render_template
from flask import url_for
name = 'Grey Li'
movies = [ {'title': 'My Neighbor Totoro', 'year': '1988'},
                            {'title': 'Dead Poets Society', 'year': '1989'},
                            {'title': 'A Perfect World', 'year': '1993'},
                            {'title': 'Leon', 'year': '1994'},
                            {'title': 'Mahjong', 'year': '1996'},
                            {'title': 'Swallowtail Butterfly', 'year': '1996'},
                            {'title': 'King of Comedy', 'year': '1999'},
                            {'title': 'Devils on the Doorstep', 'year': '1999'},
                            {'title': 'WALL-E', 'year': '2008'},
                            {'title': 'The Pork of Music', 'year': '2012'},
                            ]
app = Flask(__name__)

 @app.route('/') #前面空格需要删除,由于我博客的编辑器MarkDown不能以@开头
def index():
    return render_template('index.html',name=name,movies=movies)

  • templates文件夹下的index.html内容如下
<!DOCTYPE html> 
<html lang="en"> 
<head>
<meta charset="utf-8"> 
<title>{{ name }}'s Watchlist</title> 
</head> 
<body>
<h2>{{ name }}'s Watchlist</h2> 
{# 使用 length 过滤器获取 movies 变量的长度 #} 
<p>{{ movies|length }} Titles</p> 
<ul>
{% for movie in movies %} {# 迭代 movies 变量 #} 
<li>{{ movie.title }} - {{ movie.year }}</li> {# 等同于 movie['title'] #} 
{% endfor %} {# 使用 endfor 标签结束 for 语句 #} 
</ul> 
<footer> <small>© 2018 <a href="https://www.5yang.cc">HelloFlask</a></small> 
</footer> 
</body> 
</html>

案例效果如下

Grey Li's Watchlist
10 Titles

My Neighbor Totoro - 1988
Dead Poets Society - 1989
A Perfect World - 1993
Leon - 1994
Mahjong - 1996
Swallowtail Butterfly - 1996
King of Comedy - 1999
Devils on the Doorstep - 1999
WALL-E - 2008
The Pork of Music - 2012
© 2018 HelloFlask

提示

  • 访问 https://jinja.palletsprojects.com/en/2.11.x/templates/#list-of-builtin-filters 查看所有可用的过滤器。
最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏