Pug渲染多行JSON值显示为单行,如何添加换行?
The issue you're facing comes down to how HTML handles whitespace by default—even if your JSON string has \n line breaks, browsers collapse those into a single space when rendering plain text. Here are two straightforward solutions to preserve those line breaks in your Pug template:
1. Use a <pre> Element for Exact Formatting
The <pre> tag is designed to preserve whitespace and line breaks exactly as they appear in the source. This is perfect if you want to maintain the raw, code-like formatting of your multi-line JSON value:
Pug Template Example:
- // Sample JSON with multi-line value - const yourData = { description: "First line of text\nSecond line here\nThird line to display" } pre= yourData.description
This renders as:
<pre>First line of text Second line here Third line to display</pre>
The browser will show this as properly broken lines with the original spacing intact.
2. Convert Newlines to <br> Tags for Flowing Text
If you want the text to behave like normal paragraph content (not monospaced), you can replace \n characters with HTML <br> tags. Use Pug's unescaped output (!=) to ensure the <br> tags render as HTML instead of plain text:
Pug Template Example:
- const yourData = { description: "First line of text\nSecond line here\nThird line to display" } - // Helper function to convert newlines to <br> - const nl2br = (str) => str.replace(/\n/g, '<br>') p!= nl2br(yourData.description)
This renders as:
<p>First line of text<br>Second line here<br>Third line to display</p>
Which displays the text with natural line breaks in a standard paragraph.
Important Note for Escaped Newlines
If your JSON string has escaped newlines (e.g., "First line\\nSecond line" instead of "First line\nSecond line"), you’ll need to unescape them first. Update the helper function like this:
- const nl2br = (str) => str.replace(/\\n/g, '\n').replace(/\n/g, '<br>')
内容的提问来源于stack exchange,提问作者edusl

