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.
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 }}" />
There is a way to disable caching of the result of a particular filter: it's by not using a constant input, e.g. by exposing a random source as a global variable.
# Expose to Jinja
from random import random as RANDOM
And in the templates
{{ RANDOM() | eval_this_filter_every_time }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With