Switch Case in Django Template

3.7k views Asked by At

I'm trying to put different template for different category based on category ID. I'm using Django 1.3. Switch case is not working with Django 1.3, I get this error:

Invalid block tag: 'switch', expected 'endblock' or 'endblock content'

but switch case had been correctly closed.

Here is my code:

{% switch property.category.id %}
        {% case 0 %}
                 <h4>'agriculture'</h4>
        {% case 1 %}
                  <h4>'Residential'</h4>
        {% case 2 %}
                  <h4>'commiercial'</h4>
        {% case 3 %}
                  <h4>'mixed use'</h4>
        {% case 4 %}
                  <h4>'Industrial'</h4>
        {% else %}
                 <h4>'retail'</h4>
{% endswitch %}

What is the error in this code?

1

There are 1 answers

2
geckon On BEST ANSWER

There is no {% switch %} tag in Django template language. To solve your problem you can

  • either use this Django snippet, that adds the functionality,
  • or re-write your code to a series of {% if %}s.

The second option in code:

{% if property.category.id == 0 %}
    <h4>'agriculture'</h4>
{% elif property.category.id == 1 %}
    <h4>'Residential'</h4>
{% elif property.category.id == 2 %}
    <h4>'commiercial'</h4>
{% elif property.category.id == 3 %}
    <h4>'mixed use'</h4>
{% elif property.category.id == 4 %}
    <h4>'Industrial'</h4>
{% else %}
    <h4>'retail'</h4>
{% endif %}

As Alasdair correctly mentioned in his comment, the {% elif %} tag was introduced in Django 1.4. To use the above code in an older version you need to upgrade your Django version or you can use a modified version:

{% if property.category.id == 0 %}
    <h4>'agriculture'</h4>
{% endif %}
{% if property.category.id == 1 %}
    <h4>'Residential'</h4>
{% endif %}
{% if property.category.id == 2 %}
    <h4>'commiercial'</h4>
{% endif %}
{% if property.category.id == 3 %}
    <h4>'mixed use'</h4>
{% endif %}
{% if property.category.id == 4 %}
    <h4>'Industrial'</h4>
{% endif %}
{% if property.category.id < 0 or property.category.id > 4 %}
    <h4>'retail'</h4>
{% endif %}

This modification is safe** (but inefficient) here since the ID can't be equal to two different integers at the same time.

** as long as you only use integers for the IDs which is probable

However I would strongly recommend upgrading to a newer Django version. Not only because of the missing {% elif %} tag but mainly for security reasons.