萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Flask 模板入門:Jinja2 語法、繼承、流程控制與迴圈實戰

為什麼需要模板引擎?

在 Python 代碼中拼接 HTML 字串:難以維護、易產生 XSS、前後端耦合。Jinja2 模板引擎實現**邏輯與表現分離**,支援繼承、宏、過濾器、自動轉義。

專案結構

microblog/
├── flask/              # 虛擬環境
├── app/
│   ├── __init__.py
│   ├── views.py
│   ├── templates/
│   │   ├── base.html
│   │   └── index.html
│   └── static/
├── tmp/
└── run.py

第一個模板 templates/index.html

<html>
<head>
    <title>{{ title }} - microblog</title>
</head>
<body>
    <h1>Hello, {{ user.nickname }}!</h1>
</body>
</html>

視圖函數渲染模板

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'nickname': 'Miguel'}  # 假資料
    return render_template('index.html', title='Home', user=user)

模板繼承:base.html 佈局母版

{# templates/base.html #}
<!doctype html>
<html>
<head>
    <title>{% block title %}Microblog{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <div id="header">
        <a href="{{ url_for('index') }}">Microblog</a>
    </div>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
    <div id="footer">© 2024</div>
</body>
</html>

子模板繼承 base.html

{# templates/index.html #}
{% extends "base.html" %}

{% block title %}{{ title }} - Microblog{% endblock %}

{% block content %}
<h1>Hello, {{ user.nickname }}!</h1>
{% endblock %}

流程控制:條件判斷

{% if title %}
    <title>{{ title }} - Microblog</title>
{% else %}
    <title>Welcome to Microblog</title>
{% endif %}

迴圈渲染列表

{# views.py #}
@app.route('/')
def index():
    user = {'nickname': 'Miguel'}
    posts = [
        {'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
        {'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so cool!'}
    ]
    return render_template('index.html', user=user, posts=posts)

{# templates/index.html #}
{% for post in posts %}
<div class="post">
    <p><b>{{ post.author.nickname }}</b> says: {{ post.body }}</p>
</div>
{% else %}
<p>No posts yet.</p>
{% endfor %}

常用過濾器

過濾器用途範例
safe關閉自動轉義{{ html_content|safe }}
escape/eHTML 轉義{{ user_input|e }}
length長度{{ posts|length }}
truncate(n)截斷{{ post.body|truncate(50) }}
striptags移除 HTML 標籤{{ html|striptags }}
tojson轉 JSON{{ data|tojson }}

結語

Jinja2 模板繼承 + 區塊 + 流程控制 + 過濾器,構建出清晰可維護的前端架構。下一步:學習宏復用 UI 組件、自定義過濾器擴展功能、模板緩存提升效能。

copyright © 萬盛學電腦網 all rights reserved