【问题标题】:Django custom template tag being cachedDjango 自定义模板标签被缓存
【发布时间】:2012-12-22 22:58:25
【问题描述】:

如果您只是将链接发送到已经回答的地方,我不会生气。我还没有找到答案。

我正在一个启用了cached template loader 的网站上工作。他们有一个在许多页面上调用的自定义模板标签,传递给该标签的值之一是调用它的页面的唯一文章 ID。问题是缓存的模板加载器似乎也在缓存这些值,所以即使每个页面都将其文章 ID 传递给标签,标签仍在使用缓存的文章 ID。

有没有办法禁用单个模板标签的缓存模板加载器?

如果有帮助,这里有一些代码:

这是缓存的模板加载器设置:

TEMPLATE_LOADERS = (
    ('django.template.loaders.cached.Loader', (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )),
)

当我注释掉这个设置并重新启动服务器时,问题就消失了,所以我知道它与缓存“有关”。

上面链接的那个文档还谈到了确保模板标签是thread-safe。这是因为模板如何存储在缓存中吗?我从那个关于线程安全的注释中得到的是,传递给模板标签的值不应该分配给节点本身,而应该分配给 render_context。我在正确的轨道上吗?

这是我的代码正在执行的示例:

调用第1页的标签:

{% my_tag article_id="{{object.article_id}}" %}

调用第2页的标签:

{% my_tag article_id="{{object.article_id}}" %}

在上述两种情况下,object.article_id 都是模板变量,其中包含调用模板标签的页面的文章 ID。

下面是模板标签代码(简化)。

@register.tag(name="my_tag")
def do_my_tag(parser, token):

    article_id = None
    values = token.split_contents()
    kwargs = get_kwargs(values[1:])

    if "article_id" in kwargs:
        article_id = kwargs["id"]

    return DoMyTagNode(article_id)

class DoMyTagNode(template.Node):

    def __init__(self, article_id):
        self.article_id = article_id
        self.template = get_template('path/to/template.html')

    def render(self, context):
        article_id = Template(self.article_id).render(context)

        context.update({ 'article_id': article_id })

        return render_to_string(self.template, context)

任何帮助将不胜感激!

【问题讨论】:

    标签: django templates caching


    【解决方案1】:

    您不应该在开发中使用django.template.loaders.cached.Loader,因为这意味着您的 html 文件的更改不会被拾取,需要您重新启动服务器。这很可能是您的问题,因为您并没有真正提供更多。

    缓存的加载器不会缓存模板的输出,它会缓存文件系统中的模板。它们仍然会像没有加载器一样正常运行,所以这不是你的问题。加载程序不会缓存您的自定义标签的输出。

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 2021-07-13
      • 2015-01-20
      • 2012-03-15
      • 2015-12-17
      • 2011-03-31
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多