variablestypesflaskjinja2

check variable type inside Jinja2 in Flask


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


Solution

  • 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 Default fallback because only blocks with names available in the parent template are output).