如何在 Jinja2 中打印 \n 字符

How to print the \n character in Jinja2

我在 Python 中有以下字符串:thestring = "123\n456"

在我的 Jinja2 模板中,我使用 {{thestring}} 并且输出是:

123
456

让 Jinja2 打印准确表示 123\n456(包括 \n)的唯一方法是转义 thestring = "123\n456".

还有其他方法可以直接在模板中完成吗?

我会自己回答,也许对有同样问题的人有帮助。

这个有效:{{thestring.encode('string_escape')}}

对我来说 {{thestring.encode('string_escape')}} 失败并出现以下错误:

escape_encode() argument 1 must be string, not AnsibleUnicode

不确定我做错了什么,但以下对我来说效果很好:

{{ thestring | replace('\n','\n') }}