Lars Schneider
Lars Schneider

Reputation: 5692

Run jinja2 template_filter on every request using Flask

I generate URLs with a jinja2 template_filter using Flask:

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

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: I am new to Flask. If there is a better way to achieve the same I am also interested, of course :)

Upvotes: 2

Views: 253

Answers (1)

davidism
davidism

Reputation: 127260

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)
    }

Upvotes: 3

Related Questions