Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

jinja2 - Disable Jinja template caching for certain filter

We have a custom Jinja filter that we use for creating cache busting URL for our Javascript and CSS resources. We now noticed that in our production environment the final, compiled templates get cached. This results in a problem since our template filter sometimes doesn't create a new URL (i.e. when the template wasn't changed but the Javascript was).

Is there a way to force Jinja to reevaluate a certain filter every time and don't cache the result?

Edit 1: We are using constant inputs (name of the file) to the filter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After lots of Googling, I finally found the real solution to this. Jinja has a special helper called contextfilter that you can use to decorate your function with to make your filter context-aware (and context-dependent). The Jinja bytecode cache will not cache this computed value, even when a constant is passed as input.

In your filter in Python:

from jinja2 import contextfilter

@contextfilter
def asset_url(context, url):
    return some_url_thing(url)

In your template:

<link rel="stylesheet" href="{{ 'styles.css' | asset_url }}" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...