禁用某些过滤器的Jinja模板缓存 [英] Disable Jinja template caching for certain filter

查看:34
本文介绍了禁用某些过滤器的Jinja模板缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个自定义的Jinja过滤器,用于为Javascript和CSS资源创建缓存清除URL.现在我们注意到,在生产环境中,最终的编译模板被缓存了.这会导致问题,因为我们的模板过滤器有时不会创建新的网址(即,当模板未更改但Javascript更改时).

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

是否有一种方法可以强制Jinja每次重新评估某个过滤器并且不缓存结果?

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

编辑1 :我们正在向过滤器使用常量输入(文件名).

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

推荐答案

经过大量的Google搜索,我终于找到了真正的解决方案. Jinja有一个名为 contextfilter 的特殊帮助器,您可以用来装饰自己的函数使您的过滤器能够感知上下文(并取决于上下文).即使将常量作为输入传递,Jinja字节码缓存也不会缓存此计算所得的值.

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.

在Python过滤器中:

In your filter in Python:

from jinja2 import contextfilter

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

在您的模板中:

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

这篇关于禁用某些过滤器的Jinja模板缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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