使用Flask对每个请求运行jinja2 template_filter [英] Run jinja2 template_filter on every request using Flask

查看:109
本文介绍了使用Flask对每个请求运行jinja2 template_filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Flask jinja2 template_filter >

I generate URLs with a jinja2 template_filter using Flask:

@app.template_filter()
def generate_stuff(url):
    return do_stuff(url)

这个template_filter只对每个URL执行一次。如果用户重新加载页面,我想要再次运行此功能 Flask 。我如何做到这一点?

This template_filter is only executed once per URL. If a user reloads the page I want Flask to run this function, again. How do I do this?

PS:我是新的 Flask 。如果有一个更好的方式来实现同样的我也有兴趣,当然:)

PS: I am new to Flask. If there is a better way to achieve the same I am also interested, of course :)

推荐答案

模板过滤器是错误的使用在这里,那些是添加额外的功能,你可以使用模板中的变量。您可能正在寻找上下文处理器。您可以使用 request.url 获取URL,或者还有其他路径属性,如果这不是你想要的。

Template filters are the wrong thing to use here, those are for adding extra functions you can use against variables in templates. You're probably looking for context processors. You can use request.url to get the url, or there are other path properties on request as well if that's not what you want.

@app.context_processor
def inject_user():
    return {
        'my_stuff': do_stuff(request.url)
    }

这篇关于使用Flask对每个请求运行jinja2 template_filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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