PyIfTag - Just like python if expression

 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
from django import template
from django.utils.translation import gettext_lazy as _

register = template.Library()

class PyIfNode(template.Node):
    def __init__(self, nodeslist):
        self.nodeslist = nodeslist

    def __repr__(self):
        return "<PyIf node>"

    def render(self, context):
        for e, nodes in self.nodeslist:
            clist = list(context)
            clist.reverse()
            d = {}
            d['_'] = _
            for c in clist:
                d.update(c)
            v = eval(e, d)
            if v:
                return nodes.render(context)
        return ''

def do_pyif(parser, token):
    nodeslist = []
    while 1:
        v = token.contents.split(None, 1)
        if v[0] == 'endif':
            break
        if v[0] in ('pyif', 'elif'):
            if len(v) < 2:
                raise template.TemplateSyntaxError, "'pyif' statement requires at least one argument"
        if len(v) == 2:
            tagname, arg = v
        else:
            tagname, arg = v[0], 'True'
        nodes = parser.parse(('else', 'endif', 'elif'))
        nodeslist.append((arg, nodes))
        token = parser.next_token()
#    parser.delete_first_token()
    return PyIfNode(nodeslist)
do_pyif = register.tag("pyif", do_pyif)

More like this

  1. Bitwise operator queryset filter by hgeerts@osso.nl 3 years, 11 months ago
  2. elif for smart if tag by showell 4 years, 10 months ago
  3. sort_by_id_sequence by simon 5 years, 11 months ago
  4. Make tags easier with properties by ubernostrum 7 years, 1 month ago
  5. Yet another SQL debugging facility by miracle2k 6 years, 8 months ago

Comments

(Forgotten your password?)