如果我输入 djangotemplate.html
这段代码
<p>{% if some_custom_template %} {%some_custom_template%} {% else %} nothing {% endif %}</p>
会some_custom_template
执行两次?或者some_custom_template
结果被缓冲了?
如果some_custom_template
执行两次,我如何将第一个结果保存在某个模板变量中?
如果我输入 djangotemplate.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
实际情况。但无论如何,您都可以使用with
模板标签对其进行缓存
{% with cached_template=some_custom_template %}</p>
<p>
{% if cached_template %}
{{ cached_template }}
{% else %}
nothing
{% endif %}
</p>
{% endwith %}
编辑:在上下文中,您正在使用 custom 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>