【问题标题】:does it template tag in django execute twice?django 中的模板标签会执行两次吗?
【发布时间】:2015-04-08 10:25:56
【问题描述】:

如果我输入 django template.html 这个代码

<p>{% if some_custom_template %} {%some_custom_template%} {% else %} nothing {% endif %}</p>

some_custom_template 会执行两次吗?还是some_custom_template结果被缓冲了?

如果some_custom_template 被执行两次,我如何将第一个结果保存在一些模板变量中?

【问题讨论】:

  • 在测试用例中,some_custom_template 就是return 5。在生产中,它是一个 db-query

标签: django-templates django-custom-tags


【解决方案1】:

我相信它会被执行两次,但这取决于some_custom_template 实际上是什么。但无论如何,您都可以使用 with template tag 缓存它

{% with cached_template=some_custom_template %}</p>
    <p>
       {% if cached_template %}
         {{ cached_template }}
       {% else %}
          nothing
       {% endif %}
    </p>
{% endwith %}

编辑:在上下文中,您使用的是自定义 template_tag,这是非常不同的。是的,每次调用它们时都会生成它们,并且它们不能被缓存。

最好将显示什么的逻辑移到模板标签中,去掉模板中的if/then/else,像这样:

@simple_tag(name='unread_notification_count', takes_context=True)
def unread_notification_count(context):
  if some_check:
    return some_value
  else:
    return "nothing"

然后在模板中只需调用模板标签:

<p>{% unread_notification_count %}</p>

【讨论】:

  • 已测试 - 失败。我认为这个模板会引发TemplateSyntaxError - Invalid block tag: 'cached_template', expected 'elif', 'else' or 'endif',因为{% cached_template %} 应该是{{ cached_template }}。两种变体都不起作用。 Django 1.6.5.
  • 抱歉,我直接从问题中复制了代码,{{ cached_template }} 应该可以工作,如果您尝试这样做会发生什么?
  • {% with cached_template=some_custom_template %} 不会触发 templatetags py 文件,cached_template 总是无
  • 等等,some_custom_template 到底是什么?是变量template_tag吗?
  • 我在templatetags 文件夹中有@register.simple_tag(name='unread_notification_count', takes_context=True) def unread_notification_count(context):,在html 中有{% unread_notification_count %}{% unread_notification_count %} 工作正常。
猜你喜欢
  • 1970-01-01
  • 2014-07-25
  • 2010-12-19
  • 2018-10-21
  • 2014-03-20
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2016-12-25
相关资源
最近更新 更多