How to print the \n character in Jinja2
11,149
Solution 1
I'll answer my own, maybe it helps someone who has the same question.
This works: {{thestring.encode('string_escape')}}
Solution 2
For me {{thestring.encode('string_escape')}}
failed with the following error:
escape_encode() argument 1 must be string, not AnsibleUnicode
Not sure what I did wrong, but the following worked just fine for me:
{{ thestring | replace('\n','\\n') }}
Comments
-
boadescriptor almost 2 years
I have the following string in Python:
thestring = "123\n456"
In my Jinja2 template, I use
{{thestring}}
and the output is:123
456The only way I can get Jinja2 to print the exact representation
123\n456
(including the\n
) is by escapingthestring = "123\\n456"
.Is there any other way this can be done directly in the template?
-
OneCricketeer over 7 yearsWhy not
{{ thestring|e }}
? -
boadescriptor over 7 yearsThat doesn't seem to work with
\n
. jinja.pocoo.org/docs/dev/templates/#escape