Python Template, checking for variable value type for iteration
Question: 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](http://stackoverflow.com/questions/11947325/testing-for-a-list-in-
jinja2) 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.

