将模板标签返回值用于模板中的条件逻辑

时间:2018-06-28 14:19:59

标签: python django django-templates

我有一个返回True或False的模板标记。 例如:

@register.simple_tag
def is_home(context):
   if homepage:
       return True
   else:
       return False

我想使用此标记来更改模板中的图标:

{% if is_home %}
  <svg data-src="{% static 'images/cart_white.svg' %}" width="35" height="30"/>
{% else %}
   <svg data-src="{% static 'images/cart.svg' %}" width="35" height="30"/>
{% endif %}

然而,模板标签却不是这样。

仅当我这样称呼它时:{%is_home%}它可以工作,但是我不能将结果用作条件对象。

任何想法如何将结果用于逻辑?

1 个答案:

答案 0 :(得分:2)

simple_tag也可以用于set a variable in the context

{% is_home as is_home %}
{% if is_home %} {# now testing the `is_home` var #}
  <svg data-src="{% static 'images/cart_white.svg' %}" width="35" height="30"/>
{% else %}
   <svg data-src="{% static 'images/cart.svg' %}" width="35" height="30"/>
{% endif %}
相关问题