【问题标题】:Parsing data from database in PUG在 PUG 中从数据库中解析数据
【发布时间】:2021-12-07 04:43:45
【问题描述】:

我的 mongo 数据库中有我无法控制的数据,因为从我的应用程序导出到数据库的数据会更新 html 标签(我认为正确的术语是“编码”,但我不确定)

<div>This is some test profile text<br /></div><div><br /></div><div>Hop this prints fine<br /></div><div><br /></div><div><b>Hello</b><br /></div><div><br /></div><div>Testing</div>

在 PUG 中当我尝试用它解析它时

      .exhibitor-profile
          | !{exhibitor.profile}

打印如下

<div>This is some test profile text<br /></div><div><br /></div><div>Hop this prints fine<br /></div><div><br /></div><div><b>Hello</b><br /></div><div><br /></div><div>Testing</div>

如果我使用

      .exhibitor-profile
          | #{exhibitor.profile}

打印如下

&lt;div>This is some test profile text&lt;br />&lt;/div>&lt;div>&lt;br />&lt;/div>&lt;div>Hop this prints fine&lt;br />&lt;/div>&lt;div>&lt;br />&lt;/div>&lt;div>&lt;b>Hello&lt;/b>&lt;br />&lt;/div>&lt;div>&lt;br />&lt;/div>&lt;div>Testing&lt;/div>

与数据库中的数据基本相同..但我希望它输出为 HTML..

我该怎么做?

【问题讨论】:

  • 您的第一个示例输出 HTML。
  • 对不起,我的意思是我想呈现为 HTML .. 所以我想将它用作 HTML,但它显示为“文本”......我不确定我是否能够正确解释它..也许这是一件非常简单的事情,但我对如何使用我作为 HTML 元素所拥有的文本有点困惑
  • 在数据库中,如果我有 HTML,那么它将呈现为 HTML .. 如果我使用 | !{exhibitor.profile},数据库文本为 &lt;div&gt;&lt;b&gt;some text&lt;/b&gt;&lt;/div&gt;,那么某些文本将是粗体并且不会显示给我div 标签和 b 标签,但由于数据库中的内容是 &amp;ltl;div,它的工作方式不同..
  • 你在服务器上使用 Node 吗?
  • @OldGeezer 抱歉回复晚了。但是是的,我在服务器上使用 Node ......你有什么方法可以解决这个问题吗?

标签: html mongodb pug


【解决方案1】:

如果您使用的是 Node,请继续阅读。

安装js-htmlencode 包:

npm install -S js-htmlencode

然后通过htmlDecode 方法运行一次您的原始数据库输出。在将数据传递给 Pug 脚本之前,您应该在服务器应用程序中执行此操作:

服务器Javascript:

const htmlDecode = require("js-htmlencode").htmlDecode;
app.get("/htmldecode", (req, res) => {
  const raw = "&lt;h1>This is &lt;span style='color:red'>RED&lt;/span>!!&lt;/h1>"
  res.render("htmldecode", { raw: raw, decoded: htmlDecode(raw) })
});

htmldecode.pug:

html
  head
  body 
    h3 Html Decoding Twice
    p Using !: !{raw}
    p Using #: #{raw}
    p Final: !{decoded}

实际输出:

需要注意的是!{raw}不会渲染成&lt;h1&gt;…。它按字面意思呈现,即&amp;lt;h1&gt;…。是浏览器将&amp;lt; 显示为&lt;

请注意使用 ! 运算符时的所有注意事项。

【讨论】:

  • @AlimBolar 以上对你有用吗?
  • 将尽快测试并回复您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2016-02-14
  • 1970-01-01
  • 2018-11-27
相关资源
最近更新 更多