首页 > 解决方案 > 如何使用 Grunt 作为任务运行器在 pug 模板中导入带有数据对象的 JSON 文件?

问题描述

我有一个带有对象(字体字符的名称/代码)的 JSON 文件,我希望将它导入到 Pug 文件中,我正在使用 Grunt 作为任务运行器。

{
    "brand": 61697,
    "podcast-x": 61698,
    "podcast": 61699,
    "play": 61700,
    "book": 61702,
    "book-x": 61703,
    "map": 61704,
    "search": 61705,
    "map-x": 61706,
    "play-x": 61707,
    "eye": 61708,
    "eye-x": 61709
}

我希望在列表中显示每个字符,例如:

ul.list.list--inline
  li.list__item
    span.list__icon
      i.i.i--brand

标签: gruntjspug-loader

解决方案


首先将其添加到 grunt 任务中pug.js

module.exports = {
  options: {
    pretty: true,
    data: {
      require: require
    }
  }
};

现在只需将其包含在 pug 文件中:

block append variables
  - const icons = require('../src/images/icons/.codepoints.json')

block content
  ul.list.list--inline
    each code, name in icons
      unless name.endsWith('-x')
        li.list__item
          span.list__icon
            i.i(class='i--' + name)

            - let x = Object.keys(icons).includes(name + '-x');

            if x
              i.i(class='i--' + name + '-x')

在我的情况下,最终结果:

在此处输入图像描述


推荐阅读