Reputation: 1710
In a template in Django I am importing a list of dicts and in one of the keys (tested
) I can have either a single value or a list of values depending on the case.
My context dict in the template looks something like this:
context_dicts.append({'url': p.url,
'type_': p.type,
'error': error,
'tested': p.tested})
In the html template I want to if
test the tested
key to do something if it is a single value and something else if it's a list. So when looping through the dicts, if I use {% if value|length > 1% }
it will give me the string size of the value when it's just a value and the length of the list when it's a list. How can I test the if to tell me if it's a "list of one value" or more?
Upvotes: 0
Views: 1234
Reputation: 2629
Welcome to SO!
Storing possibly different kind of data in a single variables looks cumbersome to me. It makes your logic less easy to understand and may be prone to errors.
I think the best is to always store a list, but possibly a list with a single element. In the template, you could then do:
{% if tested.count == 1 %}
do stuff with {{ tested.0 }} value
{% else %}
do stuff with {{ tested }} list
{% endif %}
Upvotes: 1