目的是检查一个变量是否为整数,如果是,则插入“hello”。
{% if int(variable) %} hello {% endif %}
结果
'int' is undefined"
目的是检查一个变量是否为整数,如果是,则插入“hello”。
{% if int(variable) %} hello {% endif %}
结果
'int' is undefined"
int
内置过滤器(尝试将值转换为整数):你需要使用过滤器格式,就像这样:
{% if variable|int != 0 %} hello {% endif %}
默认情况下,如果将值转换为整数失败,则返回0,但您可以通过指定一个不同的默认值作为第一个参数来更改它。在这里,我已将其更改为-1,以处理0可能是variable
的有效值的情况。
{% if variable|int(-1) != -1 %} hello {% endif %}
参见:Jinja2 文档 - int 内置过滤器 以获取更多信息。
number
内置测试(如果变量已经是一个数字,则返回 true):比使用 int
过滤器更好的解决方案(它将把类似整数的字符串转换为整数)是使用内置测试 number
,如下所示:
{% if variable is number %} hello {% endif %}
对于使用Salt的用户,当我将其放在saltstack状态中时,这并没有起作用。
{% if variable|number %} hello {% endif %}
不过,这个确实起作用了:
{% if variable is number %} hello {% endif %}
{% if variable|number %}
会报错jinja2.exceptions.TemplateAssertionError: no filter named 'number'
,但是{% if variable is number %}
则能正常运行。 - kakty3