Checking the type of variable in Jinja2

Question:

I want to check the type of variable in Jinja2. If it is type of variable is dictionary then I have to print some text in the paragraph and if it’s not dict then I have to print some other values.

What I tried here is

{% if {{result}} is dict %}
<tr>
<td>
<p> The details are not here </p>
</td>
</tr>
{% else %}
{% for each_value in result %}
<tr>
<td>each_value.student_name</td>
</tr>
{% endfor %}
{% endif %}

The result I get is two different ways one is of dict type

I.result={'student_name':'a','student_id':1,'student_email':'[email protected]'}

the another format of result is

II.result=[{'student_name':'b','student_id':2,'student_email':'[email protected]','time':[{'st':1,'et':2},{'st':3,'et':4}]}]
Expected result
If I get the format 'I' then the if loop should get execute.
If I get the format 'II' then the else loop should get execute.
Actual result
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'
Asked By: user11862294

||

Answers:

You should replace {% if {{result}} is dict %} with {% if result is mapping %}.

Reference

Answered By: sashaaero

Alternative, and possibly better solutions:

{% if result.__class__.__name__ == "dict" %}

or add isinstance to Jinja context, and then

{% if isinstance(result, dict) %}

Answered By: patb
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.