烧瓶局部视图以获取项目列表

sir*_*cco 2 jinja2 flask python-2.7

如果网站的大多数页面上都有从数据库加载的类别列表或近期文章,那么如何避免使用flask和jinja2复制代码?

现在,我有一个html文件,其中包括:

{% include '/root/latest_articles.html' %}
Run Code Online (Sandbox Code Playgroud)

然后,每个视图都必须将参数(文章列表)传递给模板。我想避免这种情况。

在Flask中实现此目标的最佳方法是什么?

谢谢。

编辑

“其他模板上下文”将起作用..我可以导出一个函数,该函数从数据库加载数据并在“ latest_articles.html”模板中访问它。

还有另一种方法吗?

tbi*_*icr 5

您可以添加其他模板上下文

@app.context_processor
def additional_context():
    return {
        'content': get_page_content_context(request.endpoint, g.language),
        'hot_links': get_hot_links(),
    }
Run Code Online (Sandbox Code Playgroud)

对于模板代码,您可以使用包含

UPD:

首先,请尝试使用模板继承,如果页面允许,则将类别列表或最新文章放入基本模板中。

您也可以使用@ app.context_processor使模板代码可变,但我认为这不是一个好主意:

@app.context_processor
def additional_context():
    return {
        'recent_articles_markup': do_mark_safe(render_template(
            'root/latest_articles.html', articles=get_recent_articles()),
    }
Run Code Online (Sandbox Code Playgroud)