You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML页面中正确展示Django后端文本的换行格式

问题:Django模板中保留文本换行格式

从Django后端获取的文本包含\r\n换行符,但通过{{response.remarks}}渲染到前端时,换行消失变成连续文本,如何实现保留换行的展示效果?

后端返回的示例文本:

"Innovator in Analytical Process & Environmental Instrumentation\r\nT&C:\r\nPayment: 100% advance against PI prior to Dispatch.\r\nPrices: Ex-works Mumbai.\r\nInstl. and Comm. - Inclusive for Mumbai region. For outstation, Travel, Food\r\nand Lodging charges extra.\r\nFreight: In your scope.\r\nGST: Extra @ 18%.\r\nDelivery: 2-3 weeks after receipt of advance payment.\r\nWarranty: 1 Year from the date of installation.\r\nCustomer's scope:\r\n1. All kinds of Civil/Electrical/Plumbing works.\r\n2. Construction or Modification of the Line.\r\n3. Tubing for Sample inlet and outlet with tapping on the line with PU push\r\nconnector.\r\n4. Electrical, LAN and signal cables - Supply and laying.\r\n5. Online or Offline UPS - 1 KVA.\r\n6. SIM/LAN/Wifi/Dongle for connectivity.\r\n7. DM Water and Sulphuric Acid.\r\n8. Mounting of Flow Meter or 3-way valve.\r\n9. Lab Test Reports."

当前前端模板代码:

<ul class="list list-unstyled mb-0 text-left">
     <li><h6 class="my-1">Message Displayed </h6></li>
     <li>{{response.remarks}}</li>
</ul>

解决方案1:使用Django内置过滤器linebreaksbr

直接在模板变量后添加linebreaksbr过滤器,它会自动把文本中的\r\n或\n转换为HTML的<br>标签,实现换行:

<ul class="list list-unstyled mb-0 text-left">
     <li><h6 class="my-1">Message Displayed </h6></li>
     <li>{{ response.remarks|linebreaksbr }}</li>
</ul>

解决方案2:通过CSS样式white-space: pre-line实现

给承载文本的<li>元素添加CSS样式,让浏览器识别文本中的换行符:

<ul class="list list-unstyled mb-0 text-left">
     <li><h6 class="my-1">Message Displayed </h6></li>
     <li style="white-space: pre-line;">{{ response.remarks }}</li>
</ul>

也可以把样式写到CSS类中复用:

.text-with-linebreaks {
    white-space: pre-line;
}

模板中调用类:

<li class="text-with-linebreaks">{{ response.remarks }}</li>

pre-line会保留换行,同时自动合并连续空格,适配常规文本排版。

解决方案3:用<pre>标签包裹文本

如果需要完全保留文本的原始格式(包括空格),可以用HTML的<pre>标签:

<ul class="list list-unstyled mb-0 text-left">
     <li><h6 class="my-1">Message Displayed </h6></li>
     <li><pre>{{ response.remarks }}</pre></li>
</ul>

注意<pre>默认使用等宽字体,可通过CSS调整字体样式匹配页面风格。


内容的提问来源于stack exchange,提问作者Shweta Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:05:20