模板是一个包含响应文本的文件,其中包含用占位变量表示的动态部分,其具体值只在请求的上下文中才能知道。使用真实值替换变量,再返回最终得到的响应字符串,这一过程称为 渲染
1.模板及Jinja2模板引擎
① 渲染模板
默认情况下,Flask在程序文件夹中的 templates(样板; 模板)子文件夹中寻找模板。
Flask提供的 render_template 函数把Jinja2模板引擎集成到了程序中。
from flask import Flask, render_template
app = Flask(__name__)
render_template函数的第一个参数是模板的文件名。随后的参数都是键值对,表示模板中变量对应的真实值。
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<int:id>')
def user_id(id):
return render_template('user_id.html',id=id)
app.run()
相关模板文件(.html)如下:
<!--index.html-->
<h1>Hello World!</h1>
<!--user_id.html-->
<h1>Hello, {
{ id }}!</h1>
②变量
Jinja2能识别所有类型的变量,甚至是一些复杂的类型
# 在模板文件中访问该类的实例
class MyClass:
def func(self):
return 'This is the func in A Class'
# 在模板文件中调用该函数
def myfunc():
return 'This is a func'
@app.route('/test'