Login

elif for smart if tag

Author:
showell
Posted:
June 17, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.