- Author:
- limodou
- Posted:
- February 25, 2007
- Language:
- Python
- Version:
- Pre .96
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.