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') }}
Share:
11,149
boadescriptor
Author by

boadescriptor

Learning to program in python.

Updated on June 04, 2022

Comments

  • boadescriptor
    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
    456

    The only way I can get Jinja2 to print the exact representation 123\n456 (including the \n) is by escaping thestring = "123\\n456".

    Is there any other way this can be done directly in the template?

  • OneCricketeer
    OneCricketeer over 7 years
    Why not {{ thestring|e }}?
  • boadescriptor
    boadescriptor over 7 years
    That doesn't seem to work with \n. jinja.pocoo.org/docs/dev/templates/#escape