新行 \n 在 MongoDB Atlas 中不起作用

New Line \n Does Not Work in MongoDB Atlas

我在 MongoDB Atlas 中存储了一个带有字符串字段的文档,我用它来填充 HTML (pug) 元素。我想使用转义符 \n 在文本中指示一个新行。但是,该字符不执行转义并使用 HTML 中的文本填充“\n”,而不是开始新的文本行。

JSON 在 Mongodb 地图集

{
 "mystring" : "I want this to be two lines. \n Two lines would be great"
}

PUG代码:

p!= data.mystring

在 HTML 中呈现为:

I want this to be two lines. \n Two lines would be great

HTML 中的所需渲染:

I want this to be two lines.
Two lines would be great

FWIW,当我在 MLab 上托管时,这工作得很好。但是,我们被迫迁移到 Atlas,同样的 \n 转义似乎不起作用。

为了回应您关于 \n 来自已经转义的数据库 (\n) 的评论,您可以在 Pug 中使用正则表达式来取消转义:

- let mystring = 'I want this to be two lines. \n Two lines would be great'

p!= mystring.replace(/\n/g, '\n')

这将编译为:

<p>I want this to be two lines.
Two lines would be great</p>

但是,正如您在此堆栈片段中看到的那样,HTML 折叠了空白字符,因此它不会在浏览器中呈现为多行。

<p>I want this to be two lines.
Two lines would be great</p>


要使 HTML 呈现换行符,您需要使用 <br> 元素,正如@isAif 指出的那样。

您也可以在 Pug 中通过正则表达式插入:

- let mystring = 'I want this to be two lines. \n Two lines would be great'

p!= mystring.replace(/\n/g, '<br>\n')

这将编译为:

<p>I want this to be two lines.<br>
Two lines would be great</p>

这将在浏览器中呈现换行符,如下图所示。

<p>I want this to be two lines.<br>
Two lines would be great</p>