Stupid.Fat.Cat Stupid.Fat.Cat - 6 months ago 12
Python Question

Python Template, checking for variable value type for iteration

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.

Answer

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.