- Author:
- udfalkso
- Posted:
- July 5, 2007
- Language:
- Python
- Version:
- .96
- Tags:
- template tag list in
- Score:
- -1 (after 3 ratings)
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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 4 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks 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.