【问题标题】:Implementing django template cache in base template在基本模板中实现 django 模板缓存
【发布时间】:2017-08-13 16:38:27
【问题描述】:

我想在基础模板中实现缓存:

<!DOCTYPE html>
<html lang="en">
{% load cache %}
{% load app_config %}{% verbose_name 'polls' as app_name %}
<head>
    {% cache head %}
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %} - {{ app_name }}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'polls/css/style.css' %}" />
    {% endcache %}
</head>
<body>
    {% cache header %}
    <h2 id="header"><a href="{% url 'polls:index' %}">{{ app_name }}</a></h2><hr/>
    {% endcache %}
    {% block content %}{% endblock %}
</body>
</html>

有两个问题:

  • verbose_name 模板标签总是被执行。我怎样才能防止这种情况发生?

  • 模板标签不接受None的超时时间,即永不过期。

【问题讨论】:

    标签: django caching django-templates


    【解决方案1】:

    关于你的超时,你需要定义一个以秒为单位的超时,check documentation

    {% cache 300 header %} ... {% endcache %} # 300 seconds
    

    你需要添加一个条件来执行你的verbose_name标签

    <!DOCTYPE html>
    <html lang="en">
    {% load cache %}
    {% load app_config %}
    {% if condition %}
    {% verbose_name 'polls' as app_name %}
    {% endif %
    <head>
    

    【讨论】:

    • 我知道必须设置超时,但我想将值设置为无。 (无限)
    • 嗯,我认为 1.10 版本是不可能的。在开发版本中,他们添加了此功能。您将使用无:Documentation Developpement Version
    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 2017-10-25
    • 2011-05-13
    • 2022-11-18
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多