Templates
Flask 使用 Jinja2 作为模板引擎,用于生成 HTML。
基本用法:
python
from flask import render_template
@app.get("/")
def index():
return render_template("index.html", name="Alice")模板语法:
- 变量:
- 控制:
{% if %} ... {% endif %},{% for x in xs %} ... {% endfor %} - 过滤器:
0,可自定义过滤器 - 继承:
{% extends 'base.html' %}+{% block content %}{% endblock %}
模板目录结构:
app/
templates/
base.html
index.html示例:
html
<!-- templates/base.html -->
<!doctype html>
<title>{% block title %}Site{% endblock %}</title>
<body>
<header>Header</header>
<main>
{% block content %}{% endblock %}
</main>
</body>html
<!-- templates/index.html -->
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Hello, {{ name }}!</h1>
{% endblock %}静态文件在下一章介绍(CSS/JS/图片等)。