Given an item and a list, check if the item is in the list
-----
item = 'a'
list = [1, 'b', 'a', 4]
-----
{% ifinlist item list %}
Yup, it's in the list
{% else %}
Nope, it's not in the list
{% endifinlist %}
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 | def do_ifinlist(parser, token, negate):
bits = list(token.split_contents())
if len(bits) != 3:
raise 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 = NodeList()
return IfInListNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)
def ifinlist(parser, token):
"""
Given an item and a list, check if the item is in the list
-----
item = 'a'
list = [1, 'b', 'a', 4]
-----
{% ifinlist item list %}
Yup, it's in the list
{% else %}
Nope, it's not in the list
{% endifinlist %}
"""
return do_ifinlist(parser, token, False)
ifinlist = register.tag(ifinlist)
class IfInListNode(Node):
def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
self.var1, self.var2 = var1, var2
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.negate = negate
def __repr__(self):
return "<IfInListNode>"
def render(self, context):
try:
val1 = resolve_variable(self.var1, context)
except VariableDoesNotExist:
val1 = None
try:
val2 = resolve_variable(self.var2, context)
except VariableDoesNotExist:
val2 = None
if val1 in val2:
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
If the first term is not a variable, it gives an error, so it does not allow : {% ifinlist "constant" list %} ... {% endifinlist %} If we patch the code making val1 = self.var1 would work properly
#
Please login first before commenting.