目录

  1. 什么是模板渲染
  2. 基本模板渲染
  3. 模板继承
  4. 模板中的控制结构
  5. 静态文件与模板结合
  6. 参考资料

什么是模板渲染

Flask 使用 Jinja2 模板引擎进行模板渲染。模板渲染允许你将动态数据插入到 HTML 文件中,从而生成动态网页。它将表现层(HTML)与逻辑层(Python 代码)分开,提高代码的可维护性。


基本模板渲染

Flask 通过 render_template() 函数渲染模板文件,默认从 templates 文件夹加载。

示例

  1. 项目结构
my_app/
├── app.py
└── templates/
    └── index.html
  1. app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', name='Alice')

if __name__ == '__main__':
    app.run(debug=True)
  1. templates/index.html
    首页 ¨K17K
  • 解释
  • render_template('index.html', name='Alice'):渲染 index.html,并传递变量 name
  • {{ name }}:Jinja2 语法,在模板中显示变量值。

访问 http://127.0.0.1:5000/ 将显示 “欢迎,Alice!”。


模板继承

模板继承允许你创建一个基础模板,其他页面可以继承它以复用通用结构。

示例

  1. templates/base.html
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <header>通用头部</header>
    {% block content %}{% endblock %}
    <footer>通用底部</footer>
</body>
</html>
  1. templates/home.html
{% extends "base.html" %}
{% block title %}首页{% endblock %}
{% block content %}
    <h1>欢迎,{{ name }}!</h1>
{% endblock %}
  1. app.py

    from flask import Flask, render_template

app = Flask(name)

@app.route(‘/’)
def home():
return render_template(‘home.html’, name=’Alice’)

if name == ‘main‘:
app.run(debug=True)

  • 解释
  • {% extends "base.html" %}:继承基础模板。
  • {% block %}:定义可被子模板覆盖的区域。

模板中的控制结构

Jinja2 支持条件语句和循环,用于动态生成内容。

示例:条件和循环

templates/list.html

<!DOCTYPE html>
<html>
<head>
    <title>用户列表</title>
</head>
<body>
    <h1>用户列表</h1>
    {% if users %}
        <ul>
        {% for user in users %}
            <li>{{ user }}</li>
        {% endfor %}
        </ul>
    {% else %}
        <p>暂无用户</p>
    {% endif %}
</body>
</html>
</xaiArtifact>

**`app.py`**

python
from flask import Flask, render_template

app = Flask(name)

@app.route(‘/’)
def list_users():
users = [‘Alice’, ‘Bob’, ‘Charlie’]
return render_template(‘list.html’, users=users)

if name == ‘main‘:
app.run(debug=True)

- **解释**:
  - `{% if users %}`:条件判断。
  - `{% for user in users %}`:循环遍历列表。

---

### 静态文件与模板结合
静态文件(如 CSS、JS)存放在 `static` 文件夹中,通过 `url_for('static', filename='...')` 在模板中引用。

#### 示例
1. **项目结构**

my_app/
├── app.py
├── static/
│ └── style.css
└── templates/
└── index.html

2. **`static/style.css`**
<xaiArtifact artifact_id="9da7d0e8-ec71-4e97-909f-917cbbfc2718" artifact_version_id="fa88b0e0-6a16-4243-8ccd-b5f758c30476" title="style.css" contentType="text/css">
h1 {
    color: blue;
}
</xaiArtifact>

3. **`templates/index.html`**

html

首页

欢迎,{{ name }}!

  • 解释
  • url_for('static', filename='style.css'):生成静态文件路径。

参考资料


模板渲染是 Flask 构建动态页面的关键。如果需要更复杂的模板示例(例如表单处理或过滤器),请告诉我!