首页 › Flask Web 开发 › 模板 Jinja2
模板 Jinja2
直接在 Python 中拼接 HTML 很难维护。Flask 使用 Jinja2 模板引擎,把页面放在 templates/ 目录中。
templates/base.html:
<!doctype html>
<html>
<head><title>{% block title %}我的网站{% endblock %}</title></head>
<body>
<nav><a href="{{ url_for('index') }}">首页</a></nav>
{% block content %}{% endblock %}
</body>
</html>
templates/index.html:
{% extends "base.html" %}
{% block content %}
<h1>文章列表</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}({{ post.date }})</li>
{% else %}
<li>暂无文章</li>
{% endfor %}
</ul>
{% endblock %}
视图中渲染:
from flask import render_template
@app.route("/")
def index():
posts = [{"title": "Flask 入门", "date": "2026-11-01"}]
return render_template("index.html", posts=posts)
语法速查
{{ 变量 }}输出内容,会自动转义 HTML,防止 XSS;{% if %}、{% for %}控制结构;{{ name | upper }}过滤器;{% extends %}和{% block %}实现模板继承。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 编写模板,用表格显示学生列表,成绩低于 60 的行显示为红色。
查看参考答案
<table>
<tr><th>姓名</th><th>成绩</th></tr>
{% for s in students %}
<tr {% if s.score < 60 %}style="color:red"{% endif %}>
<td>{{ s.name }}</td><td>{{ s.score }}</td>
</tr>
{% endfor %}
</table>