如果我把在Django template.html
这个代码它在django中执行两次吗?
<p>{% if some_custom_template %} {%some_custom_template%} {% else %} nothing {% endif %}</p>
将some_custom_template
执行两次?或者some_custom_template
结果被缓冲?
如果some_custom_template
执行两次,我怎么能保存第一个结果在模板变量?
如果我把在Django template.html
这个代码它在django中执行两次吗?
<p>{% if some_custom_template %} {%some_custom_template%} {% else %} nothing {% endif %}</p>
将some_custom_template
执行两次?或者some_custom_template
结果被缓冲?
如果some_custom_template
执行两次,我怎么能保存第一个结果在模板变量?
我相信它会执行两次,但它取决于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>
谢谢,我会测试它。 – 2015-02-09 09:46:45
测试 - 失败。这个模板会引发'TemplateSyntaxError - 无效的块标记:'cached_template',我想'elif','else'或'endif',因为'{%cached_template%}'应该是'{{cached_template}}'。这两种变体都不起作用。 Django 1.6.5。 – 2015-02-09 10:30:13
对不起,我直接从问题中复制了代码,'{{cached_template}}'应该可以工作,当您尝试时会发生什么? – 2015-02-09 10:36:45
在测试用例中,'some_custom_template'只是'return 5'。在生产中,这是一个数据库查询 – 2015-02-09 06:51:54