模板#

Quart 使用 Jinja 模板引擎,该引擎经过了很好的 文档记录。Quart 在 Jinja 的默认设置中添加了标准上下文和一些标准过滤器。Quart 还添加了在应用程序和蓝图级别定义自定义过滤器、测试和上下文的能力。

在模板化时可以使用两个函数,render_template()render_template_string(),这两个函数都必须等待。这两个函数的返回值都是字符串,可以形成路由响应,也可以以其他方式组合。这两个函数都接受可变数量的额外关键字参数,以上下文的形式传递给模板,例如:

@app.route('/')
async def index():
    return await render_template('index.html', hello='world')

Quart 标准附加项#

标准上下文包括 configrequestsessiong,这些对象分别引用 current_app.configglobals 中定义的对象。可以按预期访问它们,

@app.route('/')
async def index():
    return await render_template_string("{{ request.endpoint }}")

标准全局函数是 url_for()get_flashed_messages()。这些函数可以按预期使用,

@app.route('/')
async def index():
    return await render_template_string("<a href="{{ url_for('index') }}>index</a>")

添加过滤器、测试、全局变量和上下文#

要添加在模板中使用的过滤器,请使用 template_filter()app_template_filter() 作为装饰器,或者使用 add_template_filter()add_app_template_filter() 作为函数。这些方法期望过滤器接收 Any 值并返回 str,例如:

@app.template_filter(name='upper')
def upper_case(value):
    return value.upper()

@app.route('/')
async def index():
    return await render_template_string("{{ lower | upper }}")

测试和全局变量的工作方式非常相似,只是使用测试方法和全局方法,而不是过滤器方法。

但是,上下文处理器还有一个附加功能,即它们可以在每个蓝图的基础上指定。这允许仅对路由到蓝图的请求提供上下文信息。默认情况下,context_processor() 将上下文信息添加到蓝图路由请求中,而 app_context_processor() 将信息添加到应用程序的所有请求中。一个示例,

@blueprint.context_processor
async def blueprint_only():
    return {'context': 'value'}

@blueprint.app_context_processor
async def app_wide():
    return {'context': 'value'}