【问题标题】:How to interpolate a string containing pug code within a pug file?如何在 pug 文件中插入包含 pug 代码的字符串?
【发布时间】:2018-12-28 16:08:24
【问题描述】:

我需要在 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 中,但不存在表示带有类等标签的字符串。

标签: javascript express pug string-interpolation


【解决方案1】:

您可以使用mixin 来执行此操作。 Here is a 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. 使用管道分隔符输出带有类的plain text标签
  6. 输出添加到标签的任何内容(如果存在)
  7. 关闭标签,再次使用纯文本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多