1

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':'my_name@gmail.com'}

the another format of result is

II.result=[{'student_name':'b','student_id':2,'student_email':'my_nameb@gmail.com','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 '}'
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

2

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

Reference

sashaaero
  • 2,618
  • 5
  • 23
  • 41
0

Alternative, and more general solutions, in the sense that it will work not only for mappings, but any type:

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

or add isinstance to Jinja context, and then

{% if isinstance(result, dict) %}

patb
  • 1,688
  • 1
  • 17
  • 21