将整数转换为字符串Jinja

问题:将整数转换为字符串Jinja

我有一个整数

{% set curYear = 2013 %}

{% if %}声明中,我必须将其与一些字符串进行比较。我不能curYear在开始时设置为字符串,因为我必须在循环中将其递减。

如何转换?

I have an integer

{% set curYear = 2013 %}

In {% if %} statement I have to compare it with some string. I can’t set curYear to string at the beginning because I have to decrement it in loop.

How can I convert it?


回答 0

我找到了答案。

将整数转换为字符串:

myOldIntValue|string

将字串转换为整数:

myOldStrValue|int

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

回答 1

OP需要在外部强制转换为字符串{% set ... %}。但是,如果不是您的情况,您可以执行以下操作:

{% set curYear = 2013 | string() %}

请注意,您需要在该Jinja过滤器上加上括号。

如果要串联2个变量,则还可以使用~ custom运算符

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you’re concatenating 2 variables, you can also use the ~ custom operator.