【发布时间】:2014-01-09 13:09:25
【问题描述】:
我可以使用 Grunt 成功加载一个 JSON 文件作为我的 Jade 模板的数据源,类似于 this solution。
现在我需要从项目中的不同文件夹加载一组 JSON 文件,以便可以从 Jade 模板访问其中的所有数据。如何在 Grunt 任务的上下文中做得更好?
【问题讨论】:
标签: javascript json templates gruntjs pug
我可以使用 Grunt 成功加载一个 JSON 文件作为我的 Jade 模板的数据源,类似于 this solution。
现在我需要从项目中的不同文件夹加载一组 JSON 文件,以便可以从 Jade 模板访问其中的所有数据。如何在 Grunt 任务的上下文中做得更好?
【问题讨论】:
标签: javascript json templates gruntjs pug
您可以使用此方法加载任意数量的 json 文件:
// Jade => HTML
gruntConfig.jade = {
compile: {
options: {
data: {
object: grunt.file.readJSON('JSON_FILE.json'),
object1: grunt.file.readJSON('JSON_FILE_1.json'),
object2: grunt.file.readJSON('JSON_FILE_2.json'),
}
},
}
};
然后在 Jade 模板中您只需要引用该对象。即:
script(src= object.baseURL + "js/vendor/jquery.js")
script(src= object.baseURL + "js/vendor/elementQuery.js")
script(data-main="js/main", src= object.baseURL + "js/vendor/require.js")
我知道这个问题的回答有点晚了,但对于像我一样从谷歌搜索中遇到这个问题的人来说,这是使用 Grunt.js 将多个 JSON 文件加载到 Jade 模板中的答案。
【讨论】:
您需要先组合这些对象,然后再将它们提供给 Jade。为此,我建议使用 Underscore.js。
我个人会编写一个从文件中获取数据的方法,如下所示:
module.exports = function(grunt) {
function combineJSONFiles() {
var object = {};
for(var i=0; i<arguments.length; ++i) {
_(object).extend(grunt.file.readJSON(arguments[i]));
}
return object;
}
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.initConfig(
{
jade: {
html: {
src: './*.jade',
dest: './index2.html',
options: {
client: false,
pretty: true,
data: combineJSONFiles(
"1.json",
"2.json",
"3.json"
)
}
}
}
});
grunt.registerTask('default', 'jade');
};
希望有帮助!
【讨论】: