Search code examples
jinja2

How to check if a variable is an integer in 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"

Solution

  • 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