Created
March 28, 2012 10:01
-
-
Save ojii/2225159 to your computer and use it in GitHub Desktop.
Switch-Case in the Django Template Langauge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
In Django 1.4+ you should probably use if-elif-else-endif instead of this. | |
Usage: | |
{% switch somevar %} | |
{% case 1 %} | |
... | |
{% endcase %} | |
{% case 2 %} | |
... | |
{% endcase %} | |
{% endswitch %} | |
""" | |
from classytags.arguments import Argument, Flag | |
from classytags.core import Options, Tag | |
from django.template.base import Library | |
register = Library() | |
def check(a, b, checktype): | |
if a == b: | |
return True | |
if checktype: | |
return False | |
try: | |
return unicode(a) == unicode(b) | |
except: | |
return False | |
class Switch(Tag): | |
options = Options( | |
Argument('value'), | |
Flag('checktype', true_values=['checktype'], default=False), | |
blocks=[('endswitch', 'nodelist')], | |
) | |
def render_tag(self, context, value, checktype, nodelist): | |
output = [] | |
for node in nodelist: | |
if isinstance(node, Case): | |
if check(node.value.resolve(context), value, checktype): | |
output.append(node.render(context, real=True)) | |
else: | |
output.append(node.render(context)) | |
return u''.join(output) | |
register.tag(Switch) | |
class Case(Tag): | |
options = Options( | |
Argument('value', resolve=False), | |
blocks=[('endcase', 'nodelist')], | |
) | |
def __init__(self, *args, **kwargs): | |
super(Case, self).__init__(*args, **kwargs) | |
self.value = self.kwargs['value'] | |
def render(self, context, real=False): | |
""" | |
Prevent rendering outside a switch statement | |
""" | |
if real: | |
return super(Case, self).render(context) | |
else: | |
return u'' | |
def render_tag(self, context, value, nodelist): | |
return nodelist.render(context) | |
register.tag(Case) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment