Python pattern checking variable type for iteration

Let's say that I have this dictionary

{"k1":"dog", "k2":"cat", "k3":["Pochi","Wanwan"]}

      

Now in my template I repeat like this:

{% for key, value in dict.iteritems() %}
    <tr>
        <td>{{ key }}</td>
        <td>{{ value }}</td>
    </tr>
{% endfor %}

      

But I want to do some additional processing in the tags, is it possible to check if the "value" is a list or a dictionary type? So instead of just spitting out the list, I could do something like, say, a bullet.

+3


source to share


1 answer


To check if the type of a dictionary has a "value" you can 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 %}

      

You can create your own filter to check if the list type is "value". Here is a link you will find helpful.

Edit: Here's an example of how you would create a custom filter. Function first



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

      

The filter will then be available in your template.

+1


source







All Articles