boadescriptor
boadescriptor

Reputation: 755

How to print the \n character in Jinja2

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?

Upvotes: 6

Views: 21639

Answers (2)

Vlad Nikiforov
Vlad Nikiforov

Reputation: 7015

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') }}

Upvotes: 6

boadescriptor
boadescriptor

Reputation: 755

I'll answer my own, maybe it helps someone who has the same question.

This works: {{thestring.encode('string_escape')}}

Upvotes: 6

Related Questions