Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Jinja template caching for certain filter

Tags:

jinja2

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.

like image 554
Martin Thurau Avatar asked Dec 18 '13 09:12

Martin Thurau


2 Answers

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 }}" />
like image 187
Joshua Dover Avatar answered Sep 27 '22 21:09

Joshua Dover


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 }}
like image 20
K3---rnc Avatar answered Sep 27 '22 22:09

K3---rnc