如何在Python Django temp中打印换行符

2024-05-23 09:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

{'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.'}

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

如何显示带有换行符的模板?

{{带换行符的引号\n}


Tags: youlivetodayifasitquotesgood
3条回答

使用'<br>'而不是/n

如有必要,您可以执行.replace('/n', '<br>')

使用^{}过滤器。

例如:

{{ value|linebreaks }}

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

您还可以使用^{}过滤器将所有新行简单地转换为<br> 没有额外的<p>

示例:

{{ value|linebreaksbr }}

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

Ignacio's answerlinebreaks过滤器)的区别在于linebreaks尝试猜测文本中的段落,并将每个段落包装在<p>中,其中linebreaksbr只是substitutes newlines with ^{}

下面是一个演示:

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

相关问题 更多 >

    热门问题