我希望使用 Grunt 从单个 Jade 模板创建多个 HTML 文件。
这就是我正在做的事情:
- 从外部文件获取 JSON 数据
- 循环访问该对象
- 为该 JSON 对象中的每个值创建一个 grunt 配置任务
这是我的代码:
neighborhoods = grunt.file.readJSON('data/neighborhoods.json');
for(var i = 0; i < Object.keys(neighborhoods).length; i++) {
var neighborhood = {
"title" : Object.keys(neighborhoods)[i],
"data" : neighborhoods[Object.keys(neighborhoods)[i]]
};
grunt.config(['jade', neighborhood.title], {
options: {
data: function() {
return {
neighborhoods: neighborhood.data
}
}
},
files: {
"build/neighborhoods/<%= neighborhood.title %>.html": "layouts/neighborhood.jade"
}
});
}
我遇到的问题是这个
Running "jade:Art Museum" (jade) task
Warning: An error occurred while processing a template (Cannot read property 'title' of undefined). Use --force to continue.
如果我将文件名设置为字符串,它运行正常,但显然会创建具有相同文件名的所有文件,因此只创建一个文件。我需要使该文件名动态化。
最佳答案
我在这里找到了解决方案:
Use Global Variable to Set Build Output Path in Grunt
The issue is that the module exports before those global variables get set, so they are all undefined in subsequent tasks defined within the initConfig() task.
这成功了!
var neighborhoods = grunt.file.readJSON('data/neighborhoods.json');
for(var i = 0; i < Object.keys(neighborhoods).length; i++) {
var neighborhood = {
"title" : Object.keys(neighborhoods)[i],
"data" : neighborhoods[Object.keys(neighborhoods)[i]]
};
/*
* DEFINE VALUE AS GRUNT OPTION
*/
grunt.option('neighborhood_title', neighborhood.title);
grunt.config(['jade', neighborhood.title], {
options: {
data: function() {
return {
neighborhoods: neighborhood.data,
neighborhood_title: neighborhood.title
}
}
},
/*
* OUTPUT GRUNT OPTION AS FILENAME
*/
files: {
"build/neighborhoods/<%= grunt.option('neighborhood_title') %>.html": "layouts/neighborhood.jade"
}
});
}
这会产生所需的输出:
Running "jade:East Passyunk" (jade) task
File build/neighborhoods/Society Hill.html created.
Running "jade:Fishtown" (jade) task
File build/neighborhoods/Society Hill.html created.
Running "jade:Graduate Hospital" (jade) task
File build/neighborhoods/Society Hill.html created.
Running "jade:Midtown Village" (jade) task
File build/neighborhoods/Society Hill.html created.
Running "jade:Northern Liberties" (jade) task
File build/neighborhoods/Society Hill.html created.
...
关于javascript - 使用 Grunt 从单个 Jade 模板创建多个 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24559380/