Henry Lynx
Henry Lynx

Reputation: 1129

Use template tag return value for conditional logic in template

I have a template tag that returns True or False. For example:

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

I want to use this tag to change an icon in the template:

{% 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 %}

However the template tag is not called like this.

Only if I call it like this: {% is_home %} it works but I cannot use the result for the conditional.

Any idea how can I use the result for logic?

Upvotes: 0

Views: 70

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

A simple_tag can also be used to 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 %}

Upvotes: 2

Related Questions