如何在pug文件中插入包含pug代码的字符串?

3
我需要在pug文件中插入一段包含pug格式化代码的字符串。
我已经尝试过:
- var text = "i.home.icon"

div= text
div !{text}
div #{text}
div ${${text}}
div {{text}}
div {text}
div \#{text}
div \{text}
div ${text}
div
    #{text}

我想要的是:
<div><i class="home icon"><i></div>

我不认为这是可能的。在Pug中存在标签插值,但不存在表示带类等标签的字符串。 - Sean
1个回答

1
你可以使用mixin来完成这个操作。这里有一个Codepen示例,展示了它在实际应用中的效果。
mixin tagCreator(def)
  - var tagArray = def.split('.');
  - var tag= tagArray[0];
  - tagArray.shift();
  - var classes = tagArray.join(' ');
  |<#{tag} class='#{classes}'>
  if block
    block
  |</#{tag}>

+tagCreator('one')
+tagCreator('two.three.four') Two

上述代码创建了以下HTML:
<one class=""></one>
<two class="three four">Two</two>

以下是逐行的快速解释:

  1. 将以句点分隔的字符串拆分为数组
  2. 单独存储标签名称
  3. 删除数组中的第一个元素
  4. 将其余的数组连接成适合于 class="" 输出的以空格分隔的字符串
  5. 使用管道分隔符输出带有类的 纯文本 标签
  6. 输出添加到标签中的任何内容(如果存在)
  7. 再次使用纯文本关闭标签

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接