1 # Source: http://djangosnippets.org/snippets/967/
3 # Posted: August 13, 2008
6 # We can use it based on djangosnippets Terms of Service:
7 # (http://djangosnippets.org/about/tos/)
9 # 2. That you grant any third party who sees the code you post
10 # a royalty-free, non-exclusive license to copy and distribute that code
11 # and to make and distribute derivative works based on that code. You may
12 # include license terms in snippets you post, if you wish to use
13 # a particular license (such as the BSD license or GNU GPL), but that
14 # license must permit royalty-free copying, distribution and modification
15 # of the code to which it is applied.
17 from django import template
18 from django.template import Library, Node, VariableDoesNotExist
23 @register.tag(name="switch")
24 def do_switch(parser, token):
26 The ``{% switch %}`` tag compares a variable against one or more values in
27 ``{% case %}`` tags, and outputs the contents of the matching block. An
28 optional ``{% else %}`` tag sets off the default output if no matches
31 {% switch result_count %}
33 There are no search results.
35 There is one search result.
37 Jackpot! Your search found {{ result_count }} results.
40 Each ``{% case %}`` tag can take multiple values to compare the variable
44 {% case "Jim" "Bob" "Joe" %}
45 Me old mate {{ username }}! How ya doin?
50 bits = token.contents.split()
53 raise template.TemplateSyntaxError("'%s' tag requires one argument" % tag_name)
54 variable = parser.compile_filter(bits[1])
56 class BlockTagList(object):
57 # This is a bit of a hack, as it embeds knowledge of the behaviour
58 # of Parser.parse() relating to the "parse_until" argument.
59 def __init__(self, *names):
60 self.names = set(names)
62 def __contains__(self, token_contents):
63 name = token_contents.split()[0]
64 return name in self.names
66 # Skip over everything before the first {% case %} tag
67 parser.parse(BlockTagList('case', 'endswitch'))
70 token = parser.next_token()
73 while token.contents != 'endswitch':
74 nodelist = parser.parse(BlockTagList('case', 'else', 'endswitch'))
77 raise template.TemplateSyntaxError("'else' must be last tag in '%s'." % tag_name)
79 contents = token.contents.split()
80 token_name, token_args = contents[0], contents[1:]
82 if token_name == 'case':
83 tests = map(parser.compile_filter, token_args)
84 case = (tests, nodelist)
88 case = (None, nodelist)
91 token = parser.next_token()
94 raise template.TemplateSyntaxError("'%s' must have at least one 'case'." % tag_name)
96 return SwitchNode(variable, cases)
99 class SwitchNode(Node):
100 def __init__(self, variable, cases):
101 self.variable = variable
105 return "<Switch node>"
108 for tests, nodelist in self.cases:
109 for node in nodelist:
112 def get_nodes_by_type(self, nodetype):
114 if isinstance(self, nodetype):
116 for tests, nodelist in self.cases:
117 nodes.extend(nodelist.get_nodes_by_type(nodetype))
120 def render(self, context):
122 value_missing = False
123 value = self.variable.resolve(context, True)
124 except VariableDoesNotExist:
129 for tests, nodelist in self.cases:
131 return nodelist.render(context)
132 elif not value_missing:
134 test_value = test.resolve(context, True)
135 if value == test_value:
136 return nodelist.render(context)