views:

1738

answers:

3

Hi, I found a link to have a 'switch' tag in Django templates, but I was wondering if this can be somehow achieved without it. Using only the stuff which comes with Django? Basically is there other way then using multiple 'if' or 'ifequal' statements?

Thanks in advance for any tips/suggestions.

+11  A: 

Unfortunately, this is not possible with the default Django template engine. You'll have to write something ugly like this to emulate a switch.

{% if a %}
    {{ a }}
{% else %}
    {% if b %}
        {{ b }}
    {% else %}
        {% if c %}
            {{ c }}
        {% else %}
            {{ default }}
        {% endif %}
    {% endif %}
{% endif %}

or if only one if condition can be true and you don't need a default.

{% if a %}
{{ a }}
{% endif %}
{% if b %}
{{ b }}
{% endif %}
{% if c %}
{{ c }}
{% endif %}

Usually, when the template engine is not powerful enough to accomplish what you want this is a sign that the code should be moved into Django view instead of in the template. For example:

# Django view
if a:
  val = a
elif b:
  val = b
elif c:
  val = c
else:
  val = default

# Template
{{ val }}
+2  A: 

In a very general view, the need for a switch statement is a sign that there is a need to create new classes and objects that capture the different "cases".

Then, instead of "swtich"ing all over the place, you only need to call an object method or reference an object attribute and your done.

Ber
+5  A: 

To the previous responders: Without understanding the use case, you've made assumptions and criticized the questioner. @Ber says "all over the place" which is certainly not implied by the questioner. Not fair.

I have a case where I would like to do a {%switch%} statement in exactly one place in my Django template. Not only is it not convenient to move the equivalent of the switch statement into Python code, but that would actually make both the view and the template harder to read and take simple conditional logic that belongs in one place and split it into two places.

In many cases where I could imagine a {%switch%} (or an {%if%}) being useful, not using one requires putting HTML in a view. That's a far worse sin and is why {%if%} exists in the first place. {%switch%} is no different.

Fortunately, Django is extensible and multiple people have implemented switch. Check out:

http://www.djangosnippets.org/snippets/967/

Roy Leban