Say that I have this dictionary
{"k1":"dog", "k2":"cat", "k3":["Pochi","Wanwan"]}
Now in my template, I'm iterating like so:
{% for key, value in dict.iteritems() %}
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
But I do want to do some additional processing within the tags, is it possible to check if "value" is of a list or dictionary type? So that instead of just spitting out the list, I could do things like, say bullet them.
To check if "value" is of a dictionary type you could do something like
{% for key, value in dict.iteritems() %}
<tr>
<td>{{ key }}</td>
{% if value is mapping %}
"Do something"
{% else %}
<td>{{ value }}</td>
</tr>
{% endfor %}
To check if "value" is of a list type, you could create a custom filter. Here's a link you would find useful.
Edit: Here's an example of how you would create a custom filter. First the function
def is_list(value):
return isinstance(value, list)
Then declare the function as a filter
from flask import Flask
app = Flask(__name__)
....
app.jinja_env.filters['is_list'] = is_list
Then the filter will be available in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With