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

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

如何在模板中显示这些换行符?

{{quotes|withlinebreaks\n}}

5个回答

110

使用linebreaks过滤器。

例如:

{{ value|linebreaks }}
如果值为Joel\nis a slug,输出结果将为<p>Joel<br />is a slug</p>

40
您还可以使用linebreaksbr过滤器仅将所有换行符转换为<br>,而不需要额外的<p>
示例:
{{ value|linebreaksbr }}
如果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'

2
这样更好,我不知道为什么人们会投错答案。 - Lord-shiv
1
这个解决方案帮助我保留了CSS设置。使用{{value|linebreaks}}的顶部解决方案忽略了它们。 - Anthony M

2
所有这些答案都没有明确提到在显示模板中应该使用{{ value|linebreaksbr }},即在获取请求而不是提交请求中使用。

因此,如果您有一个用于显示post.details的模板,它应该是:

<h4>Below are the post details</h4>

{{ post.details|linebreaksbr }}

而不是在提交表单中

<form method="post">
    {% csrf_token %}
    {{ form|linebreaksbr }}
    <button>Save post</button>
</form>

我曾经遇到过同样的问题,后来解决了,觉得有人可能会觉得这个信息很有用。 祝你编程愉快!


0
由于某些原因,我无法更改这个值。
val = """
Brand AER \nDetail Material Kuningan berlapis emas chrome dan powder coating \nTipe Produk Keran Shower \nWarna Emas \nMaterial Kuningan \nUkuran Kemasan 12cm x 19cm x 13cm \nUkuran Barang 12cm x 19cm x 13cm \nBerat 2kg \nManual Instruksi instalasi manual dapat didownload di link berikut:https://aer.co.id/products/aer-kran-shower-panas-dingin-luxury-series-sah-sr1/?attachment_id=10954&amp;download_file=5e267c93cdc76&amp;_wpnonce=28db09bc61
"""

其中包含'\n',需要使用换行符或linebreaksbr过滤器进行换行处理 我已经尝试过这个方法

{ val|linebreaks }}
{ val|linebreaksbr }}

val 保持不变,然后我尝试了 @AndrewFox 的答案并且对我起作用了

\n 更改为 <br> 并关闭自动转义

{% autoescape off %}
   {{ val }}
{% endautoescape %}

-5

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

如果需要,可以使用 .replace('/n', '<br>')


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接