Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is an integer in Jinja2?

Tags:

jinja2

The aim is to check whether a variable is an integer and if that is true insert hello.

Attempt

{% if int(variable) %} hello {% endif %}

Result

'int' is undefined"
like image 963
030 Avatar asked Jan 19 '17 14:01

030


1 Answers

To use the Jinja2 int builtin filter (which tries to cast the value to an int):

You need to use the filter format, like this:

{% if variable|int != 0 %} hello {% endif %}

By default, if casting to int fails it returns 0, but you can change this by specifying a different default value as the first parameter. Here I've changed it to -1 for a case where 0 might be a valid value for variable.

{% if variable|int(-1) != -1 %} hello {% endif %}

see the: Jinja2 Docs - int builtin filter for more info

To use the Jinja2 number builtin test (which returns true if the variable is already a number):

a better solution, rather than using the int filter (which will cast a integer like string to an int) is to use the builtin test number, like this:

{% if variable is number %} hello {% endif %}

see the: Jinja2 Docs - number builtin test

like image 81
abigperson Avatar answered Sep 18 '22 11:09

abigperson