Convert integer to string Jinja

PythonJinja2Nunjucks

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Solution 2 - Python

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.

Solution 3 - Python

could use this on set_fact in ansible

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGlen SwiftView Question on Stackoverflow
Solution 1 - PythonGlen SwiftView Answer on Stackoverflow
Solution 2 - Pythonlouis_guittonView Answer on Stackoverflow
Solution 3 - Python张馆长View Answer on Stackoverflow