我知道這是一箇舊帖子,但我一直試圖解決類似的問題,但我一直在這裏回來。我想使用for-loop從單個模板文件輸出多個html文件。所以需要更好地控制'文件'對象。
我遇到並最終解決的兩個問題是設置輸出文件名(javascript對象文字KEY)並確保內聯javascript函數立即運行,以便循環變量可用。
這是我的完整源代碼和評論。我希望這對任何其他人在這篇文章中陷入困境都有用。
Gruntfile.js:
module.exports = function(grunt) {
// Create basic grunt config (e.g. watch files)
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
grunt: { files: ['Gruntfile.js'] },
jade: {
files: 'src/*.jade',
tasks: ['jade']
}
}
});
// Load json to populate jade templates and build loop
var json = grunt.file.readJSON('test.json');
for(var i = 0; i < json.length; i++) {
var obj = json[i];
// For each json item create a new jade task with a custom 'target' name.
// Because a custom target is provided don't nest options/data/file parameters
// in another target like 'compile' as grunt wont't be able to find them
// Make sure that functions are called using immediate invocation or the variables will be lost
// http://stackoverflow.com/questions/939386/immediate-function-invocation-syntax
grunt.config(['jade', obj.filename], {
options: {
// Pass data to the jade template
data: (function(dest, src) {
return {
myJadeName: obj.myname,
from: src,
to: dest
};
}()) // <-- n.b. using() for immediate invocation
},
// Add files using custom function
files: (function() {
var files = {};
files['build/' + obj.filename + '.html'] = 'src/index.jade';
return files;
}()) // <-- n.b. using() for immediate invocation
});
}
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-contrib-watch');
// Register all the jade tasks using top level 'jade' task
// You can also run subtasks using the target name e.g. 'jade:cats'
grunt.registerTask('default', ['jade', 'watch']);
};
SRC/index.jade:
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) {
bar(1 + 5)
}
body
h1 #{myJadeName} - node template engine
#container.col
p.
Jade is a terse and simple
templating language with a
strong focus on performance
and powerful features.
test.json:
[{
"id" : "1",
"filename" : "cats",
"tid" : "2016-01-01 23:35",
"myname": "Cat Lady"
},
{
"id" : "2",
"filename" : "dogs",
"tid" : "2016-01-01 23:45",
"myname": "Dog Man"
}]
運行 '咕嚕' 後的輸出應爲:
build/cats.html
build/dogs.html
嘗試'文件:{「源/模板/ out.html:[ '源/模板/ *玉']}' – elclanrs
我想將它們編譯成多個文件,而不是一個單一的文件 – LandonSchropp
哦。我看......通過尋找一個在文檔好像擴展添加這樣的'分機:」 .html'',以點無法看到的問題是什麼?你試過沒有'cwd'剛?的完整路徑來測試 – elclanrs