Login

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

Author:
danilchenko
Posted:
February 16, 2011
Language:
Python
Version:
1.2
Tags:
template if elif django 1.2 tags. tag
Score:
2 (after 2 ratings)

Adds to Django 1.2 tag {% elif %}

{% 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 %}

Snipped designed for gaeframework.com

Inspired by snippets: #1572 and #2243

 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

Comments

danilchenko (on February 16, 2011):
<p>Tested with nested conditions on Django 1.2.5</p> <pre>{% 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 %} </pre>

#

danilchenko (on February 16, 2011):
<p>FIXED: bug with return None if conditions in "if" tag is False</p>

#

pierrei (on July 13, 2016):
<p>I just started using this snippet with Django 1.3 and it seemed to be working well until I used it with offline compression of static assets.</p> <p>After a lot of debugging I managed to find the problem; the IfNode class in your implementation does not implement the "nodelist" property. If found this while looking at the Django 1.4 implementation of IfNode.</p> <p>This fixes the issue:</p> <pre>class IfNode(Node): def __init__(self, branches): self.branches = branches def __repr__(self): return "<If node>" def __iter__(self): for branch in self.branches: for node in branch.node_list: yield node @property def nodelist(self): return NodeList(self.__iter__()) def render(self, context): for n in self.branches: var = n.var if var is not True: try: var = var.eval(context) except VariableDoesNotExist: var = None if var: return n.node_list.render(context) return "" </pre>

#

Please login first before commenting.