T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 57 天:Jinja 模板:动态页面与博客首页

这是「Python 100 天」系列第 57 天的学习笔记:Jinja 模板:动态页面与博客首页。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

做一个博客首页:从 API 拉文章列表,用 Jinja 的循环把每篇文章渲染成一张卡片;点进 /post/1 看详情。README 知识点:用 Jinja 生成动态 HTML、Jinja 与 API 结合、多行语句、url_for 构建 URL。

一、Jinja 的三个核心语法

1
2
3
4
5
6
7
8
9
10
11
<!-- 1. 变量:双花括号 -->
<h1>{{ post.title }}</h1>

<!-- 2. 语句:花括号加百分号,用于循环/判断 -->
{% for post in posts %}
<li>{{ post.title }}</li>
{% endfor %}

{% if posts|length > 0 %}
<p>共 {{ posts|length }} 篇</p>
{% endif %}
  • {{ }} 输出值,会自动做 HTML 转义(防 XSS);
  • {% %} 控制结构,不输出内容;
  • {# #} 注释,不会出现在最终 HTML 里。

二、传数据给模板

1
2
3
4
@app.route("/blog")
def get_blog():
all_posts = requests.get(BLOG_URL).json()
return render_template("index.html", posts=all_posts)

模板里就能用 posts 这个变量。模板只能访问你显式传进去的东西,不能直接读 Python 的全局变量。

三、url_for:不要手写 URL

1
<a href="{{ url_for('find_post', post_id=post.id) }}">{{ post.title }}</a>

url_for('函数名', 参数=值) 会根据路由规则反推出 URL。好处:

  • 路由改了(/post/<id> → /p/<id>),模板不用改;
  • 自动处理特殊字符和前缀。

四、过滤器

1
2
3
4
{{ post["body"][:100] }}...      <!-- 截断,Python 切片在 Jinja 里也能用 -->
{{ post.title|title }} <!-- 首字母大写 -->
{{ posts|length }} <!-- 长度 -->
{{ text|safe }} <!-- 不转义(危险,慎用) -->

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from flask import Flask, render_template
import requests


BLOG_URL = "https://api.npoint.io/c790b4d5cab58020d391"
app = Flask(__name__)


@app.route('/')
def home():
return render_template("index.html")


@app.route("/blog")
def get_blog():
response = requests.get(BLOG_URL)
all_posts = response.json()
return render_template("index.html", posts=all_posts)


@app.route("/post/<int:post_id>")
def find_post(post_id):
response = requests.get(BLOG_URL)
all_posts = response.json()
if post_id == 1:
return render_template("post.html", posts=all_posts)
if post_id == 2:
return render_template("post2.html", posts=all_posts)
if post_id == 3:
return render_template("post3.html", posts=all_posts)


if __name__ == "__main__":
app.run(debug=True)

代码走读

  1. BLOG_URL 指向 npoint.io(一个免费的 JSON 托管服务),返回 3 篇文章,每篇有 id、title、subtitle、body。
  2. / 渲染首页,/blog 拉数据后渲染同一个 index.html,但传了 posts。
  3. /post/<int:post_id> 按 id 返回不同的模板文件。

这份代码的问题(很重要)

(1) 按 id 硬编码模板

1
2
3
4
if post_id == 1:
return render_template("post.html", posts=all_posts)
if post_id == 2:
return render_template("post2.html", posts=all_posts)

3 篇文章要 3 个模板文件,30 篇就要 30 个。正确做法是一个模板 + 选出对应那篇文章:

1
2
3
4
5
6
7
@app.route("/post/<int:post_id>")
def find_post(post_id):
posts = requests.get(BLOG_URL).json()
post = next((p for p in posts if p["id"] == post_id), None)
if post is None:
return "文章不存在", 404
return render_template("post.html", post=post)

(2) 每次请求都调 API

/blog 和 /post/1 各请求一次,页面多了会把免费接口打挂。应该缓存(functools.lru_cache 或存文件)。

(3) 没传 posts 给 /

home() 只 render_template("index.html"),如果模板里有 {% for post in posts %},会因为 posts 未定义而渲染为空(Jinja 默认不报错,容易误以为"没数据")。

(4) post.py 里只有 class Post: pass

是个占位文件,说明作者本来想用类建模,最后没做。这就是"设计先行、实现跟上"的半成品,读别人代码时会经常见到。

运行结果

/blog 页面是三张卡片,每张有标题、副标题、正文前 100 字和"Read More";点进去是详情页。

易错点

  1. posts 是列表,模板里用了 posts.title:应该 {% for post in posts %} 再 post.title。
  2. 字典取值:post.title 在 Jinja 里对字典也有效(等价 post["title"]),但键含空格时必须用 post["a b"]。
  3. url_for 的函数名是 Python 函数名,不是路径。
  4. HTML 转义:正文里有 <script> 会被转义成文本,这是保护,不是 bug。

动手改

  • 用一个 post.html 替换三个模板。
  • 加 404 处理:文章不存在时返回友好页面。
  • 用 @lru_cache 缓存 API 结果。

源文件逐个讲解

7 个文件(不含 static/images/ 里的几张配图):

文件 行数 职责
main.py36三个路由:首页、博客列表、单篇文章
post.py2空类(只有一个 pass)
templates/index.html47博客首页:三张卡片
templates/post.html28第 1 篇文章页
templates/post2.html28第 2 篇文章页
templates/post3.html28第 3 篇文章页
static/css/styles.css70博客样式

这一天最重要的不是代码,而是「它有多烂」——三个模板几乎逐字相同,这正好是 Day 59 要解决的问题。

main.py(36 行)

(1)数据来自 npoint.io

1
BLOG_URL = "https://api.npoint.io/c790b4d5cab58020d391"

npoint.io 是一个「在线 JSON 存储」服务——你把一段 JSON 贴上去,它给你一个 URL。用来模拟「后端 API」,不用自己写服务器。

返回的结构是:

1
2
3
4
5
[
{"id": 1, "title": "...", "subtitle": "...", "body": "..."},
{"id": 2, ...},
{"id": 3, ...}
]

(2)首页:render_template 不传数据

1
2
3
@app.route('/')
def home():
return render_template("index.html")

index.html 里用了 {% for blog_post in posts %}——但 posts 没传。

Jinja2 遇到未定义的变量不会报错,而是当成 Undefined:{% for %} 循环零次,卡片是空的。

所以访问 / 会看到一个「有标题、有三张空卡片」的页面——不崩,但没内容。

这是 Jinja 的一个特性,也是陷阱:拼错的变量名不会报错,只会静默不显示。

(3)/blog:传数据

1
2
3
4
5
@app.route("/blog")
def get_blog():
response = requests.get(BLOG_URL)
all_posts = response.json()
return render_template("index.html", posts=all_posts)

render_template("index.html", posts=all_posts):第二个参数起,都是「往模板里塞的变量」。

模板里的 posts 就拿到这个列表。

同一个模板被两个路由用——/ 不传数据、/blog 传数据。这是设计失误:应该让 / 直接重定向到 /blog,或者两边都传。

(4)/post/<int:post_id>:三个 if 挑模板

1
2
3
4
5
6
7
8
9
10
@app.route("/post/<int:post_id>")
def find_post(post_id):
response = requests.get(BLOG_URL)
all_posts = response.json()
if post_id == 1:
return render_template("post.html", posts=all_posts)
if post_id == 2:
return render_template("post2.html", posts=all_posts)
if post_id == 3:
return render_template("post3.html", posts=all_posts)

这段代码有三个明显问题:

① 每个 if 都返回同一个 all_posts(全部文章):

模板里再用 {% if blog_post["id"] == 1 %} 挑出那一篇——「挑哪篇」这件事被拆成了两处:

  • Python 里选模板文件(post.html / post2.html / post3.html)
  • 模板里选数据(if id == 1/2/3)

这是典型的「该在 Python 做的事放到了模板里」。

② post_id 是 4 时,三个 if 都不成立 → 函数返回 None → Flask 报错:

1
TypeError: The view function for 'find_post' did not return a valid response.

正确的做法是 abort(404):

1
2
3
4
5
from flask import abort
post = next((p for p in all_posts if p["id"] == post_id), None)
if post is None:
abort(404)
return render_template("post.html", post=post)

③ 每次请求都重新 requests.get:三次点击 = 三次 HTTP 请求。应该缓存。

post.py(2 行)——一个空类

1
2
class Post:
pass

就两行。这是一个「占位文件」——作者本打算建一个 Post 类来封装文章数据(self.id、self.title…),但没写。

它被 main.py 导入了吗?没有。 这个文件完全没被用到。

但它是一个「预告」:Day 59 会真的建 Post 类(post.py 里会有 __init__ 和三个属性)。

templates/index.html(47 行)

(1)三张卡片,结构完全一样

1
2
3
4
5
6
7
8
9
10
11
    <div class="content">
<div class="card">
{% for blog_post in posts: %}
{% if blog_post["id"] == 1: %}
<h2>{{ blog_post["title"] }}</h2>
<p>{{ blog_post["subtitle"] }}</p>
{% endif %}
{% endfor %}
<a href="{{ url_for('find_post', post_id=1) }}">Read</a>
</div>
</div>

把这段复制三遍,只改 id == 1 → 2 → 3——这是全书最典型的「复制粘贴」反面教材。

正确写法(Day 58 之后会学到):

1
2
3
4
5
6
7
{% for blog_post in posts %}
<div class="card">
<h2>{{ blog_post.title }}</h2>
<p>{{ blog_post.subtitle }}</p>
<a href="{{ url_for('find_post', post_id=blog_post.id) }}">Read</a>
</div>
{% endfor %}

一个循环搞定,加第 4 篇文章不用改模板。

(2)Jinja 语法:{% ... %} 和 {{ ... }}

写法 含义
{{ x }}输出变量的值(转义 HTML)
{% for %} / {% if %}控制流(不输出)
{# ... #}注释

注意 {% for blog_post in posts: %} 末尾的冒号——这不是 Jinja 语法要求,是作者从 Python 习惯带过来的。Jinja 允许,但多余。

(3)url_for('find_post', post_id=1)

url_for(函数名, 参数) 反向生成 URL:

1
url_for('find_post', post_id=1)   # → "/post/1"

为什么不用写死 "/post/1"? 因为路由规则改了(比如改成 /p/<id>),url_for 会自动跟着变。这是 Flask 推荐的做法——Day 56 的 static/ 硬编码就该这么改。

(4)href="../static/css/styles.css" 是个真 bug

1
<link rel="stylesheet" href="../static/css/styles.css">

.. 是「上一级目录」:

  • 访问 /blog(一层)→ ../static/... 解析成 /static/... ✓ 能用
  • 访问 /post/1(两层)→ ../static/... 解析成 /post/static/... ✗ 404

结果是:博客首页有样式,文章页没样式。

正确写法:

1
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">

这个 bug 在四个模板里都有——因为是从同一个模板复制的。

(5)<footer> 在 </body> 外面

1
2
3
4
5
</body>
<footer>
<p>Made with ♥️ in Toronto.</p>
</footer>
</html>

<footer> 跑到了 <body> 之后、</html> 之前——这是非法的 HTML 结构。浏览器会容错(把它挪回 body 里),但验证器会报错。

四个模板全有这个问题。

post.html / post2.html / post3.html(各 28 行)

三个文件逐字相同,只差一个数字:

1
2
3
4
5
6
7
                {% for blog_post in posts: %}
{% if blog_post["id"] == 1: %}
<h1>{{ blog_post["title"] }}</h1>
<h2>{{ blog_post["subtitle"] }}</h2>
<p>{{ blog_post["body"] }}</p>
{% endif %}
{% endfor %}

post2.html 是 == 2,post3.html 是 == 3。

这 84 行代码,本质上只需要 1 个模板 + 1 个参数:

1
2
3
4
5
@app.route("/post/<int:post_id>")
def find_post(post_id):
posts = requests.get(BLOG_URL).json()
post = next(p for p in posts if p["id"] == post_id)
return render_template("post.html", post=post)
1
2
3
<h1>{{ post.title }}</h1>
<h2>{{ post.subtitle }}</h2>
<p>{{ post.body }}</p>

这就是「模板复用」——Day 58 的 Jinja 教程就是讲这个。

另外注意:三个模板里 {% if %} 之外没有任何「文章不存在」的处理——如果 post_id 对不上,页面是空白的(不是 404)。

static/css/styles.css(70 行)

大部分是卡片布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
.wrapper {
position: relative;
clear: both;
margin: 0 auto 75px auto;
width: 100%;
overflow: hidden;
}

.top {
background: #4e89ae;
height: 180px;
border-top: 20px solid #43658b;
}

clear: both:清除前面浮动的影响(经典 clearfix 思路,但 overflow: hidden 才是真正的 BFC 修复)。

border-top: 20px solid 做「页头深色条」——用边框当装饰条,比多加一个 div 省事。

这份代码的问题

  1. post.html / post2.html / post3.html 三份重复(最严重)。
  2. index.html 三张卡片复制三遍。
  3. href="../static/..." 在深层路由 404(4 个模板都有)。
  4. <footer> 在 <body> 外(4 个模板都有)。
  5. post.py 是空类,没有被使用。
  6. / 不传 posts,首页卡片是空的。
  7. post_id > 3 返回 None,Flask 报 500。
  8. 每个请求都重新拉 API。

README.md(9 行)

标题 Day 57 - Templating with Jinja in Flask Applications,知识点:Jinja、URL Building、Multi-line statements、Jinja Templates。

这一天的代码「能用但很丑」——而丑的原因正是 Jinja 没用好。Day 58 的 Bootstrap 和 Day 59 的重构,就是来收拾这个摊子的。

微信收款码 微信
支付宝收款码 支付宝
评论