178

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?

revelt
  • 2,312
  • 1
  • 25
  • 37
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79

3 Answers3

328

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int
Ajoy
  • 1,838
  • 3
  • 30
  • 57
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79
  • What page did you find that on? – Sergio Aug 14 '15 at 18:56
  • @Sergio heh, I don't remember, that was several years ago :) – Boris Zagoruiko Nov 01 '15 at 12:04
  • 4
    Confirmed to work on nunjucks (which is based on jinja) on (email) HTML builds. That's how to convert numeric string values to integers. Btw, in my case I've got integers as strings coming from JSON content files: `"hero_title_img_w": "111"` and `"hero_title_img2_w": "222"`. Then I'm adding them in .NJK file: `{{ hero_title_img_w|int + hero_title_img2_w|int }}` to use as image's `width` attribute. Hope it helps somebody one day. – revelt Oct 26 '16 at 12:56
  • 2
    For those wanting the docs, this is a builtin filter: https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters – Elias Dorneles May 07 '20 at 10:25
8

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.

HackDolphin
  • 166
  • 11
louis_guitton
  • 5,105
  • 1
  • 31
  • 33
2

Formatting someInt as a string can be achieved through:

'{0:d}'.format(someInt)

This syntax come from ansible, that also uses Python and Jinja. behind the scene.

Uriel
  • 182
  • 3
  • 10
张馆长
  • 1,321
  • 10
  • 11