首页 > 解决方案 > 如何使用 pug 在 JS 中插入 html 标签?

问题描述

当我需要在 JS 中使用类似 JSON 的对象时,每个块中都有不同的数据并遍历该对象时,我通过 pug 创建了一个 HTML 代码。

让我用代码描述一下

var footerMenu = {
   left: {
      title: "sometitle",
      list: [
         {
         title: "First thing to do",
         text:  "wake up and brush some teeth"
         },

         {
         title: "Second thing to do",
         text:   "start coding"
         },
(...)

当带有属性的文本footerMenu.left[0].text必须使用某些标签进行样式设置时,问题就来了。

我需要这样的东西

...... text: "wake up and #[span.color-red brush] some teeth"

但是,当然 pug 将其读取为简单的字符串。

我不想手动编写每个块,如何保存相同的代码结构但使用 pug 将随机标签应用到我的 JSON 对象中?

标签: javascriptjsonpughtml-preprocessor

解决方案


您可以像通常这样编写 html 标签:

text: "wake up and <span class='color-red brush'>some teeth</span>"

然后在 pug 中,您可以使用如下未转义的属性

.some-class!=footerMenu.left[0].text

或使用未转义的字符串插值属性

.some-class !{footerMenu.left[0].text}

推荐阅读