Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 996
Rakib Avatar asked May 21 '13 17:05

Rakib


People also ask

How do you check if a variable exists in Jinja?

If variable is always evaluated to True when not None, {% if variable != None %} is equivalent to {% if variable %} .

Does Jinja2 have flask?

Flask comes packaged with Jinja2, and hence we just need to install Flask. For this series, I recommend using the development version of Flask, which includes much more stable command line support among many other features and improvements to Flask in general.

Which data type we use for send values in Jinja?

Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine.


2 Answers

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).

like image 76
Sean Vieira Avatar answered Sep 17 '22 15:09

Sean Vieira


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 %} 
like image 25
Vasili Pascal Avatar answered Sep 19 '22 15:09

Vasili Pascal