Login

{% ifthis FOO isoneof BAR BAZ ... %}

Author:
sjl
Posted:
May 14, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

Probably not thread safe, but good enough for the moment.

 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
class IfThisNode(template.Node):
    '''
    Like {% if %} but checks if the first value is equal to any of the rest.

    Example:

        {% ifthis username isoneof 'steve' 'nick' var_with_other_username %}
            ...
        {% else %}
            ...
        {% endifthis %}
    '''
    def __init__(self, var, items, nodelist_true, nodelist_false, case_sensitive):
        self.var, self.items = var, items
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.case_sensitive = case_sensitive

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

    def render(self, context):
        def _parse_var(var):
            if var.startswith('\'"'):
                return var[1:-1]
            else:
                return template.resolve_variable(var, context)

        var = _parse_var(self.var)
        items = map(_parse_var, self.items)

        if not self.case_sensitive:
            try:
                var = var.lower()
            except AttributeError:
                pass
            
            for n, item in enumerate(items):
                try:
                    items[n] = item.lower()
                except AttributeError:
                    pass

        if var in items:
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

def ifthis(parser, token, case_sensitive=True):
    bits = token.split_contents()
    if len(bits) < 4:
        raise template.TemplateSyntaxError, (
            "%r takes at least two arguments" % bits[0]
        )

    if bits[2] != 'isoneof':
        raise template.TemplateSyntaxError, (
            "%r must be of the format {% %r FOO isoneof BAR BAZ ... %}"
            % (bits[0], 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 IfThisNode(
        bits[1], bits[3:],
        nodelist_true, nodelist_false, case_sensitive
    )

register.tag('ifthis', ifthis)
register.tag('insensitiveifthis', lambda p, t: ifthis(p, t, False))

More like this

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

Comments

pakalk (on May 16, 2010):

What is the difference between ifthis username isoneof 'steve' 'nick' var_with_other_username and if item in []?

#

Please login first before commenting.