Bixly How-To: do elif and switch in django template

Branching in Django templates is handled mainly by the {% if %} tag. However, while the {% tag %} can have a corresponding {% else %}, it does not have {% elif %}. This is in line with the policy that Django templates should contain as little logic as possible. You should try to do with only {% if %} and {% else %} and more complicated logic in views. However, you may encounter cases where it is easier and cleaner to do logic more complicated than a single if but still simple enough to remain in the template.
The elif behavior can of course be reproduced by nesting {% if %} in {% else %}:

However, the long line of {% endif %} quickly becames hard to keep up with. Thankfully, the extensibility of the Django template language and this code snippet: http://djangosnippets.org/snippets/2360/ make it possible to have {% elif %} functionality in Django templates. Simply save the snippet as a custom template tag and remember to decorate the do_if function with @register.tag(name=’if’). Also remember that the tag needs to be loaded each time you use it in a template.

After that you should be able to use {% elif %} in Django templates:

The switch branching construct is also absent from the Django template language. It’s not present in Python itself, of course, but since there is also no access to dicts and assigning to dicts in Django template language, using switch becomes the cleaner way of branching on the value of an expression (cleaner than a lot of similar looking elif’s that is). Again, a code snippet helps us out: http://djangosnippets.org/snippets/967/

Both {% switch %} and {% if %} with {% elif %} can be nested with themselves and each other. Both snippets were tested to be working on Django 1.3 but should also work on earlier Django versions.