繁体   English   中英

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

[英]How to print line breaks in Python Django template

{'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|带换行符\n}}

使用linebreaks过滤器。

例如:

{{ value|linebreaks }}

如果 value 是Joel\\nis a slug ,则输出将是<p>Joel<br />is a slug</p>

您还可以使用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'

出于某种原因,我无法更改此值

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 %}

所有这些答案都没有明确提到{{ 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>

遇到了同样的问题,在弄清楚之后,我们决定外面的人可能会觉得它很方便。 快乐编码!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM