Login

{% if %} tag with {% elif %} support

Author:
amagee
Posted:
October 26, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Django tempalte tag that supports {% elif %} branches.

  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
 98
 99
100
101
102
"""

Django template tag that supports {% elif %} branches.

Usage:

  {% my_if a == 0 %}
    a == 0 
  {% elif a == 1 %}
    a == 1
  {% elif a == 2 %}
    a == 2
  {% else %}
    a not in [0, 1, 2]
  {% endif %}


Requires a small patch to django to work properly:

Index: __init__.py
===================================================================
--- __init__.py	(revision 14358)
+++ __init__.py	(working copy)
@@ -264,7 +264,7 @@
                 var_node = self.create_variable_node(filter_expression)
                 self.extend_nodelist(nodelist, var_node,token)
             elif token.token_type == TOKEN_BLOCK:
-                if token.contents in parse_until:
+                if token.contents.partition(" ")[0] in parse_until:
                     # put token back on token list so calling code knows why it terminated
                     self.prepend_token(token)
                     return nodelist

"""


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

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 "<MyIf 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


def do_if(parser, token):
  branches = []

  bits = token.split_contents()[1:]
  var = TemplateIfParser(parser, bits).parse()

  end_nodes = (('else', 'elif', 'endif'))

  node_list = parser.parse(end_nodes)
  branches.append(IfBranch(var, node_list))
  token = parser.next_token()

  while token.contents == "else" or token.contents.startswith("elif"):
    if token.contents.startswith("elif"):
      bits = token.split_contents()[1:]
      var = TemplateIfParser(parser, bits).parse()
    else:
      var = True

    node_list = parser.parse(end_nodes)
    branches.append(IfBranch(var, node_list))
    token = parser.next_token()

  parser.delete_first_token()
  return IfNode(branches)

do_if = register.tag("my_if", do_if)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

sandeepp (on March 18, 2014):

How can I use it. I mean where to put this code and then how to call it. Thanks

#

Please login first before commenting.