Login

"If in" template tag

Author:
andrew
Posted:
April 24, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Makes new template tags "ifin" and "ifnotin".

 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
# Almost all of this code is from ifequal in django/template/defaulttags.py
# Common code should be factored out into a "if <function>" tag creator, and patch and posted on trac?

# Put this in your templatetags directory, of course

from django.template import Library, TemplateSyntaxError, Node, NodeList, Variable, VariableDoesNotExist

register = Library()

class IfInNode(Node):
    def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
        self.var1, self.var2 = Variable(var1), Variable(var2)
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.negate = negate

    def __repr__(self):
        return "<IfInNode>"

    def render(self, context):
        try:
            val1 = self.var1.resolve(context)
        except VariableDoesNotExist:
            val1 = None
        try:
            val2 = self.var2.resolve(context)
        except VariableDoesNotExist:
            val2 = None
        try:
            if (self.negate and val1 not in val2) or (not self.negate and val1 in val2):
                return self.nodelist_true.render(context)
            return self.nodelist_false.render(context)
        except TypeError:
            raise ValueError, "Second arg to ifin or ifnotin must be iterable"

def do_ifin(parser, token, negate):
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise TemplateSyntaxError, "%r takes two arguments" % bits[0]
    end_tag = 'end' + bits[0]
    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = NodeList()
    return IfInNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)

def ifin(parser, token):
   return do_ifin(parser, token, False)
register.tag('ifin', ifin)

def ifnotin(parser, token):
    return do_ifin(parser, token, True)
register.tag('ifnotin', ifnotin)

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

djypsy (on May 2, 2008):

Technically speaking, this is more like a is_iterable tag as opposed to a ifin tag. In the render method, a check is made to see the source var is iterable, rather than a more pure containment check.

For instance, consider this contrived snippet:

class Foo(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __contains__(self, what):
        return what in self.__dict__ or what in self.__dict__.values()

An instance of Foo would generate cause the TypeError exception, yet it clearly supports the in opertion:

>>> f = Foo(a=1, b='asdf', c=range(4))            
>>> 'a' in f
True
>>> 'asdf' in f
True

Instead of Look before you leap checking, consider Better to ask forgiveness... by replacing the iter check with your conditional.

#

andrew (on May 15, 2008):

You're right. I modified the code to be more "Better to ask forgiveness". Do you think the last try/except should be removed altogether?

#

Please login first before commenting.