如何为每个编译的jade文件提供不同的data.json?

时间:2013-09-30 10:54:08

标签: pug gruntjs frontend environment

我在GruntJS上跑步很新。我正在使用Jade,Sass和Grunt配置一个简单的开发环境。

目的是生成解析给定JSON的不同类型的模板。我目前的配置如下:

jade: {
        html: {
                options: {
                    client: false,
                    pretty: true,
                    data: grunt.file.readJSON("src/data.json")
                },
                src: 'src/index.jade',
                dest: 'build/index.html'

        }   
}

我想要那样的东西:

jade: {
        html: {
                files: [
                    {
                        options: {
                           client: false,
                           pretty: true,
                           data: grunt.file.readJSON("src/A/data.json")
                        },
                        src: 'src/A/index.jade',
                        dest: 'build/A/index.html'
                    },
                    {
                        options: {
                           client: false,
                           pretty: true,
                           data: grunt.file.readJSON("src/B/data.json")
                        },
                        src: 'src/B/index.jade',
                        dest: 'build/B/index.html'
                    },
                    {
                        options: {
                           client: false,
                           pretty: true,
                           data: grunt.file.readJSON("src/C/data.json")
                        },
                        src: 'src/C/index.jade',
                        dest: 'build/C/index.html'
                    }   
                ]
         }

}

这种情况有解决方案吗?

提前谢谢!

1 个答案:

答案 0 :(得分:2)

在Grunt中,您可以为每个目标或每个任务设置选项:

jade: {
  options: { /* task level options */ },
  htmlA: { // <- this is a target name
    options: {
      // target level options override the task level
      client: false,
      pretty: true,
      data: grunt.file.readJSON("src/A/data.json")
    },
    src: 'src/A/index.jade',
    dest: 'build/A/index.html'
  },
  htmlB: {
    options: {
      client: false,
      pretty: true,
      data: grunt.file.readJSON("src/B/data.json")
    },
    src: 'src/B/index.jade',
    dest: 'build/B/index.html'
  },
}

尽管grunt-contrib-jade中的data选项也接受了一个函数,所以最好以编程方式更好地执行它:

jade: {
  html: {
    options: {
      client: false,
      pretty: true,
      data: function(dest, src) {
        var path = require('path');
        // Resolve data.json in the first src folder
        return grunt.file.readJSON(path.resolve(path.dirname(src[0]), 'data.json'));
      }
    },
    files: (function() {
      var files = {};
      // Build A-Z files
      for (var i = 65; i <= 90; i++) {
        var chr = String.fromCharCode(i);
        files['build/' + chr + '/index.html'] = 'src/' + chr + '/index.jade';
      }
      return files;
    }())
  }
}