1.前面的例子中(第一篇),业务逻辑和表现逻辑混合在了一起,会导致代码难以理解和维护。因此, 把表现路基移到模板中能提升程序的可维护性。
例:用户在网站仲注册了一个新账户。用户在变淡中输入嗲子邮箱地址和密码,然后点击提交按钮。服务器收到包含用户输入数据的请求,然后Flask把请求分发到处理请求的视图函数。这个视图函数需要访问数据库,添加新用户,然后生成响应回送浏览器。
其中:服务器收到包含用户输入数据的请求,然后Flask把请求分发到处理请求的视图函数,被称为业务逻辑。
这个视图函数需要访问数据库,添加新用户,然后生成响应回送浏览器,被称为表现逻辑。
2.模板是一个包含响应文本的文件,其中包含用展位变量表示的动态部分,变量的具体指只在请求的上下文中才能知道。使用真实值替换变量,再返回最终得到的响应字符串,这一过程称为渲染。Flask使用jinja2作为模板渲染引擎。
3.渲染模板
例:
from flask import Flask, render_template
# ...
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
新函数render_template()为jinja2提供。这样,Flask在程序文件夹中的子文件夹中寻找模板。第一个参数是文件名,随后的参数都是键值对(name=name),表示模板中变量对应的真实值。下面,让我们看一下render_template()函数的源码。
4.源码
def render_template(template_name, **context):
"""Renders a template from the template folder with the given
context.
:param template_name: the name of the template to be rendered
:param context: the variables that should be available in the
context of the template.
"""
current_app.update_template_context(context)
return current_app.jinja_env.get_template(template_name).render(context)
可以看到,render_template函数通过current_app.update_template_context(context)
来表达context,即上下文变量(例子中的name),最后返回current_app.jinja_env.get_template(template_name).render(context)
的结果,使用env的模板环境加载名为‘tempalte_name’的模板文件,并且渲染上下文变量(.render(context))。
重点在.jinja_env.get_template()
函数中,jinja2模板中。
这里留作记号,回头再读jinja2模板。抱歉。