[英]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 }}
如果value
是Joel\\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&download_file=5e267c93cdc76&_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.