1 min read

Flask 模板渲染

Flask 采用 Jinja2 模板引擎,框架会从 templates 文件夹查找模板文件。

官方手册示例

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

模块 VS 包

项目类型不同,模板引擎查找模板文件的相对位置会有所差异。

CASE 1: module

/application.py
/templates
    /hello.html

CASE 2: package

/application
    /__init__.py
    /templates
        /hello.html

渲染模板

render_template() 方法的第一个参数为模板名,第二个参数是一个参数列表,主要用在模板文件的上下文中。

app.py

from flask import Flask, render_template

@app.route('/')
def index():
    mydata = {'title': '您好', 'greet': '世界你好!'}
    return render_template('hello.html', data=mydata, title='I'm Jinja')

templetes/hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ title }}</title>
</head>
<body>
    {{ data.greet }}
</body>
</html>