现在位置: 首页 > Flask 教程 > 正文

Flask 模板渲染 API

Flask 使用 Jinja2 引擎渲染模板,将 Python 数据嵌入 HTML 页面。

模板文件默认放在项目根目录的 templates/ 文件夹中。


render_template

最常用的模板渲染函数,从文件加载模板并渲染。

参数 类型 说明
template_name_or_list str / list 模板文件名(相对于 templates 文件夹),或模板名列表(返回第一个存在的)
**context 关键字参数 传递给模板的变量,如 title="Hello", user=user_obj

全部渲染函数

函数 说明
render_template(template_name_or_list, **context) 从文件渲染模板,返回 HTML 字符串
render_template_string(source, **context) 从字符串渲染模板,适用于嵌入式模板
stream_template(template_name_or_list, **context) 流式渲染模板,返回生成器。适用于大型页面
stream_template_string(source, **context) 流式渲染字符串模板
get_template_attribute(template_name, attribute) 获取模板中的宏或变量。可从 Python 调用 Jinja2 宏

模板中的内置对象

以下对象在模板中无需显式传递即可使用:

对象 说明
request 当前请求对象
session 当前 Session 对象
g 请求级全局对象
config 应用配置字典
url_for URL 生成函数
get_flashed_messages Flask 消息获取函数

代码示例

实例

from flask import Flask, render_template, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html",
                          title="RUNOOB 首页",
                          posts=[{"id": 1, "title": "文章A"},
                                 {"id": 2, "title": "文章B"}])

@app.route("/inline")
def inline_template():
    # 从字符串渲染(模板内容直接写在代码中)
    return render_template_string("""
        <h1>Hello, {{ name }}!</h1>
        <p>Welcome to RUNOOB.</p>
    """
, name="World")

@app.route("/stream")
def stream_large_page():
    # 流式渲染大页面,边生成边发送
    return stream_template("large_report.html",
                          items=get_10k_items())