Django 1.2 template tag {% IF %} with {% ELIF %} support

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Django 1.2 template tag that supports {% elif %} branches.

Usage:

    {% if user.nick == "guest" %}
      Hello guest!
    {% elif user.nick == "admin" or user.is_admin %}
      Hello admin!
    {% elif user %}
      You are registered user
    {% else %}
      Login to site
    {% endif %}

Use it without any change in the django template!

Register new template tag:

 # in Django:
     from django.template import Library
     register = Library()
     do_if = register.tag("if", do_if)

 # in Google App Engine:
     from google.appengine.ext.webapp.template import create_template_register
     register = create_template_register()
     register.tag("if", do_if)

@author: Anton Danilchenko (http://gaeframework.com)
"""

from django.template import Library
from django.template import Node, VariableDoesNotExist
from django.template.defaulttags import TemplateIfParser

register = Library()


class IfBranch(object):
    def __init__(self, var, node_list):
        self.var = var
        self.node_list = node_list


class IfNode(Node):
    def __init__(self, branches):
        self.branches = branches

    def __repr__(self):
        return "<If node>"

    def __iter__(self):
        for n in self.branches:
            for node in n:
                yield node

    def render(self, context):
        for n in self.branches:
            var = n.var
            if var != True:
                try:
                    var = var.eval(context)
                except VariableDoesNotExist:
                    var = None
            if var:
                return n.node_list.render(context)
                break
        return ""


def do_if(parser, token):
    class Enders(list):
        def __contains__(self, val):
            return val.startswith('elif') or val in ('else', 'endif')
    
    enders = Enders()
    branches = []
    
    while True:
        contents = token.split_contents()
        bits = contents[1:]
        if contents[0] in ("if", "elif"):
            var = TemplateIfParser(parser, bits).parse()
            nodelist = parser.parse(enders)
            next_token = parser.next_token()
            branches.append(IfBranch(var, nodelist))
            token = next_token
        elif token.contents == 'else':
            nodelist = parser.parse(('endif',))
            parser.delete_first_token()
            branches.append(IfBranch(True, nodelist))
            break
        elif token.contents == 'endif':
            break

    return IfNode(branches)

More like this

  1. elif for smart if tag by showell 4 years, 10 months ago
  2. Accordion changelist admin by djm 3 years, 4 months ago
  3. {% if %} tag with {% elif %} support by amagee 3 years, 5 months ago
  4. Improved User Admin by gregb 3 years, 11 months ago
  5. Admin Save and view next button html by ungenio41 3 years, 11 months ago

Comments

danilchenko (on February 16, 2011):

Tested with nested conditions on Django 1.2.5

{% if user.nick == "guest" %}
  Hello guest!
{% elif user.nick == "admin2" or user.is_admin2 %}
  {% if user.nick == "guest" %}
    Hello guest!
  {% elif user.nick == "admin2" or user.is_admi2n %}
    Hello admin !!!
  {% elif user2 %}
    You are registered user!!!
  {% else %}
    Login to site 123
  {% endif %}
{% elif user2 %}
  You are registered user
{% else %}
  Login to site
{% endif %}

#

danilchenko (on February 16, 2011):

FIXED: bug with return None if conditions in "if" tag is False

#

(Forgotten your password?)