如何在Python Django模板中打印换行符

TIM*_*MEX 25 html python django templates

{'quotes': u'Live before you die.\n\n"Dream as if you\'ll live forever, live as if you\'ll die today"\n\n"Love one person, take care of them until you die. You know, raise kids. Have a good life. Be a good friend. Try to be completely who you are, figure out what you personally love and go after it with everything you\'ve got no matter how much it takes." -Angelina Jolie.'}
Run Code Online (Sandbox Code Playgroud)

注意我的字典中有换行符:\n

如何使用这些换行符显示模板?

{{报价| withlinebreaks \n}}

Ign*_*ams 63

使用linebreaks过滤器.

例如:

{{ value|linebreaks }}
Run Code Online (Sandbox Code Playgroud)

如果值为Joel\nis a slug,则输出为<p>Joel<br />is a slug</p>.


Bur*_*ash 9

您还可以使用linebreaksbr过滤器将所有换行符简单地转换为,<br> 而无需添加其他内容<p>

例:

{{ value|linebreaksbr }}
Run Code Online (Sandbox Code Playgroud)

如果valueJoel\nis a slug,则输出为Joel<br>is a slug

Ignacio的答案linebreaks过滤器)的不同之处在于,它linebreaks试图猜测文本中的段落并将每个段落都包装在<p>其中,而用来linebreaksbr简单地替换换行符<br>

这是一个演示:

>>> from django.template.defaultfilters import linebreaks
>>> from django.template.defaultfilters import linebreaksbr
>>> text = 'One\nbreak\n\nTwo breaks\n\n\nThree breaks'
>>> linebreaks(text)
'<p>One<br />break</p>\n\n<p>Two breaks</p>\n\n<p>Three breaks</p>'
>>> linebreaksbr(text)
'One<br />break<br /><br />Two breaks<br /><br /><br />Three breaks'
Run Code Online (Sandbox Code Playgroud)

  • 这更好我不知道为什么人们投票给错误的答案。 (2认同)