Login

elif for smart if tag

Author:
showell
Posted:
June 17, 2009
Language:
Python
Version:
1.0
Tags:
template smart_if
Score:
0 (after 0 ratings)

The code posted here adds "elif" functionality to the smart if snippet 1350.

To use the snippet first follow the instructions for installing smart_if, then swap in the method shown on the left for the original smart_if method. You'll need to keep all the supporting classes from the original implementation, of course.

You can use it like this:

{% if 0 %}
  {% if 1 %}
    Hello Venus
  {% else %}
    unexpected
   {% endif %}
{% elif 0 %}
  Hello Earth
{% elif 0 %}
  Foo 
{% else %}
  Hello Mars 
{% endif %}

The code is compatible with original smart_if classes as of June 2009, and the use of "contains" in the Enders class relies on the current implementation of Parser.parse, which says "if token.contents in parse_until:" in the one place it uses the parse_until parameter, which seems like stable code to me.

The code works by recursively creating SmartIfNodes for the elif clauses.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def smart_if(parser, token):
    if_elifs = []
    if_spelling = 'if'
    
    class Enders(list):
        def __contains__(self, val):
            return val.startswith('elif') or val in ['else', 'endif']
    enders = Enders()
                
    while True:
        contents = token.split_contents()
        command = contents[0]
        bits = contents[1:]
        if command == if_spelling:
            var = TemplateIfParser(parser, bits).parse()
            nodelist = parser.parse(enders)
            next_token = parser.next_token()
            if_elifs.append((var, nodelist, token))
            if_spelling = 'elif'
            token = next_token
        elif token.contents == 'else':
            nodelist_false = parser.parse(('endif',))
            parser.delete_first_token()
            break
        elif token.contents == 'endif':
            nodelist_false = None
            break
    while len(if_elifs) > 1:
        var, nodelist_true, token = if_elifs.pop()
        false_node = SmartIfNode(var, nodelist_true, nodelist_false)
        nodelist_false = parser.create_nodelist()
        parser.extend_nodelist(nodelist_false, false_node, token)
    var, nodelist_true, token = if_elifs[0]
    return SmartIfNode(var, nodelist_true, nodelist_false)

More like this

  1. Django 1.2 template tag {% IF %} with {% ELIF %} support by danilchenko 4 years, 4 months ago
  2. PyIfTag - Just like python if expression by limodou 8 years, 4 months ago
  3. in_list filter by guychi 7 years, 10 months ago
  4. Counter model - run multiple persistent counters by simon 6 years ago
  5. Pagination Alphabetically compatible with paginator_class by vascop 3 years, 2 months ago

Comments

Please login first before commenting.