Django does not have ability to write {% if "item" in list %}, so I had to write this tag. It can be used just like ifequal 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 45 46 47 48 49 50 51 52 | from django import template
from django.template import Variable, VariableDoesNotExist
register = template.Library()
class IfContainsNode(template.Node):
def __init__(self, iterable_name, val, nodelist_true, nodelist_false, negate):
self.iterable, self.val = Variable(iterable_name), val
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.negate = negate
def __repr__(self):
return "<IfContainsNode>"
def render(self, context):
try:
iterable = self.iterable.resolve(context)
except VariableDoesNotExist:
iterable = []
if (self.negate and self.val in iterable) or \
(not self.negate and self.val in iterable):
return self.nodelist_true.render(context)
return self.nodelist_false.render(context)
@register.tag
def ifcontains(parser, token):
return do_ifcontains(parser, token, False)
@register.tag
def ifnotcontains(parser, token):
return do_ifcontains(parser, token, True)
def do_ifcontains(parser, token, negate):
bits = list(token.split_contents())
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()
if not bits[2][0] == bits[2][-1] and bits[2][0] in ('"', "'"):
raise template.TemplateSyntaxError, \
"%r tag's third argument should be in quotes" % bits[0]
return IfContainsNode(bits[1], bits[2][1:-1], nodelist_true, nodelist_false, negate)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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.