如何避免在使用基本模板时重复上下文建立过程? [英] How to avoid duplicating context-setting-up procedure when using base template?

查看:199
本文介绍了如何避免在使用基本模板时重复上下文建立过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jinja2 时,基本的骨架模板通常会被其他模板扩展。

我的基本模板需要在上下文中的某些变量,到处都使用这个基本模板,我必须复制设置过程。

例如,我可能需要阅读一些从数据库类别名称,并将它们呈现为标题中的列表,现在我必须在任何地方使用基本模板编写此查询。



有什么方法可以避免当使用 jinja2

解决方案

时可以添加这些代码上下文处理器到您的应用程序或蓝图。这些将额外的值注入到Jinja上下文中。这些不是任何视图的一部分,但会在请求上下文中运行,因此您可以访问视图中的所有内容。

 <$ c 
$ author':'davidism',
'last_update':interesting_function()

ase_context():
返回{头文件':db.query(MyModel.category).distinct()。all()
}





传递到 render_template的上下文 c $ c>函数将覆盖这些默认的上下文值(如果它们具有相同的密钥)。


When using jinja2, base "skeleton" template are often extended by many other templates.

One of my base templates require certain variables in the context, and everywhere I use this base template I have to duplicate the setting up procedure.

For example, I may need to read some category names from DB and render them as a list in the header, now I have to write this query everywhere I use the base template.

What are some good way to avoid duplicating these kind of code when using jinja2?

解决方案

You can add context processors to your app or blueprint. These inject extra values into the Jinja context. These aren't part of any view, but will run in the request context so you have access to everything you normally would in a view.

@app.context_processor
def base_context():
    return {
        'author': 'davidism',
        'last_update': interesting_function()
        'headers': db.query(MyModel.category).distinct().all()
    }

Processors added on a blueprint are only available to templates rendered from a view on that blueprint.

Context passed to the render_template functions will override these default context values (if they have the same key).

这篇关于如何避免在使用基本模板时重复上下文建立过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆