"If in" templatetag

 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
class IfInNode(template.Node):
    '''
    Like {% if %} but checks for the first value being in the second value (if a list). Does not work if the second value is not a list.
    '''
    def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
        self.var1, self.var2 = var1, var2
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.negate = negate

    def __str__(self):
        return "<IfNode>"

    def render(self, context):
        val1 = template.resolve_variable(self.var1, context)
        val2 = template.resolve_variable(self.var2, context)
        try:
            val2 = list(val2)
            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 TypError:
            return ""

def ifin(parser, token, negate):
    bits = token.contents.split()
    if len(bits) != 3:
        raise template.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 = template.NodeList()
    return IfInNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)

register.tag('ifin', lambda parser, token: ifin(parser, token, False))

More like this

  1. "If in" template tag by andrew 5 years, 12 months ago
  2. "for" template tag with support for "else" if array is empty by jezdez 6 years, 3 months ago
  3. Delicious Tag by alcides 5 years, 10 months ago
  4. custom template tag sample by shinyzhu 4 years, 2 months ago
  5. split_contents2 for template tags by bl4th3rsk1t3 4 years, 10 months ago

Comments

mikeivanov (on April 16, 2007):

Hi bitprophet,

how about a trivial filter like this:

@register.filter
def in_list(value,arg):
    return value in arg

which you would use like this:

The item is 
{% if item|in_list:list %} 
    in list 
{% else %} 
    not in list
{% endif %}

#

Archatas (on April 17, 2007):

I also have a solution analogous to bitprophet's one, that is template tag {% ifcontains list value %}{% endifcontains %}

But I prefer the straightforward solution by mikeivanov.

#

bitprophet (on April 18, 2007):

I, too, actually prefer mikeivanov's filter solution! Wonder why that didn't occur to me when I wrote the tag version :)

#

dokterbob (on October 12, 2008):

mikeivanov, your solution seems only to work for lists of strings.

#

(Forgotten your password?)