Login

PyIfTag - Just like python if expression

Author:
limodou
Posted:
February 25, 2007
Language:
Python
Version:
Pre .96
Tags:
tag
Score:
5 (after 5 ratings)

How to use it

{% pyif i == 1 %}
    <p>i=1</p>
{% elif i == 3 %}
    <p>i=3</p>
{% else %}
    <p>other</p>
{% endif %}

Warning: For now, django don't support elif, so you can use it. And I'v submit a patch about to fix it ( #3090 ). If the patch is accepted, you can use elif tag.

 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 4 years, 10 months ago
  2. elif for smart if tag by showell 5 years, 9 months ago
  3. sort_by_id_sequence by simon 6 years, 10 months ago
  4. Make tags easier with properties by ubernostrum 8 years ago
  5. Yet another SQL debugging facility by miracle2k 7 years, 7 months ago

Comments

Please login first before commenting.