44

The template file i created contains this:

{% if type({'a':1,'b':2}) is dict %}
    print "Oh Yes!!"
{% else %}
    print "Oh No!!!"
{% endif %}

Then Jinja2 responds by saying:

TemplateAssertionError: no test named 'dict'

I am completely new to Jinja2 and Flask

Rakib
  • 12,376
  • 16
  • 77
  • 113

3 Answers3

58

You are looking for the mapping test:

{% if {'a': 1, 'b': 2} is mapping %}
    "Oh Yes!"
{% else %}
    "Oh No!"
{% endif %}

Jinja is not Python though, so you don't have access to all the builtins (type and print do not exist, for example, unless you add them to the context. In Flask, you do this with the context_processor decorator).

You don't actually need print at all. By default everything is output (unless you are in a child template that extends a parent, in which case you can do interesting things like the NULL Master fallback because only blocks with names available in the master template are output).

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
14

In case you want to get a custom type you can access field name like in this example:

  {% if 'RelationField' in field.__class__.__name__ %}
      <div class="col-md-1">
      Manage object
      </div>
  {% endif %}
Vasili Pascal
  • 3,102
  • 1
  • 27
  • 21
  • This gives me an error, but at least it does print the type: `access to attribute '__class__' of 'timedelta' object is unsafe.` – Marco Roy Mar 17 '22 at 14:38
13

How about:

{% if {'a':1,'b':2} is mapping %}
    print "Oh Yes!!"
{% else %}
    print "Oh No!!!"
{% endif %}

see List of Builtin Tests for reference.

Tommi Komulainen
  • 2,830
  • 1
  • 19
  • 16