刚刚通过 Using Assemble 找到了解决方案,使用一个模板文件从多个数据文件生成 HTML 文件?.
稍微修改了示例以加载动态模板:
'use strict';
var _ = require('lodash');
var path = require('path');
module.exports = function(grunt) {
// expand the data files and loop over each filepath
var pages = _.flatten(_.map(grunt.file.expand('./src/data/*.json'), function(filepath) {
// read in the data file
var data = grunt.file.readJSON(filepath),
fileTemplate = grunt.file.read("./src/templates/" + data.template);
// create a 'page' object to add to the 'pages' collection
return {
// the filename will determine how the page is named later
filename: path.basename(filepath, path.extname(filepath)),
// the data from the json file
data: data,
// add the recipe template as the page content
content: fileTemplate
};
}));
// Project configuration.
grunt.initConfig({
config: {
src: 'src',
dist: 'dist'
},
assemble: {
pages: {
options: {
flatten: true,
assets: '<%= config.dist %>/assets',
layout: '<%= config.src %>/templates/layouts/default.hbs',
partials: '<%= config.src %>/templates/partials/**/*.hbs',
// add the pages array from above to the pages collection on the assemble options
pages: pages
},
files: [
// currently we need to trick grunt and assemble into putting the pages file into the correct
// place using this pattern
{ dest: './dist/', src: '!*' }
]
}
}
});
grunt.loadNpmTasks('assemble');
grunt.registerTask('default', [
'assemble'
]);
};