用grunt生成模板 – 寻找任务

我有一个包含以下内容的HTML文件:

<html> <body> <span>{{ secret }}</span> </body> </html> 

我正在寻找一个可以采取这个源文件的咕task任务,拿一个值的映射:

 grunt.initConfig({ myTask: { myTarget: { src: ... dest: ... values: { secret: 'ABC' } } } }) 

并生成输出文件:

 <html> <body> <span>ABC</span> </body> </html> 

有没有这样的任务? 我看到了grunt-mustache-html,但它强制许多事情存在,我真的不需要,我不想使用它。 我只想简单地拿一个小胡子(或hbs或其他),用来自grunt-level对象的数据填充它,然后将结果转储到另一个HTML文件中,就这些了。

您可以尝试处理lo-dash模板的 grunt- template 。 以下是解决您的问题的基本设置:

 //Gruntfile.js config.template = { myTask: { options: { data: function () { return { secret: 'ABC' }; } }, files: { 'output.html: ['template.html.tpl'] } } }; //template.html.tpl <html> <body> <span><%= secret %></span> </body> </html> 

#1 。 一个select是使用grunt.template实用程序(请参阅lagerone的答案)。 使用自定义分隔符,您可以实现非常接近的结果:

 grunt.template.addDelimiters('myDelimiters', '{{', '}}'); 

在这种情况下,您的模板将不得不使用{{= secret }}标签。

#2 。 另一种select是,你总是可以写你自己的简单的任务。 在你的情况下,它可以看起来像这样:

 grunt.initConfig({ myTask: { options: { data: { secret: 'ABC' }, src: 'index.html', dest: 'index.output.html' } } }); grunt.registerTask('myTask', function() { var options = this.options(), template = grunt.file.read(options.src); var content = template.replace(/\{\{\s*(.*?)\s*\}\}/g, function(a, b) { return typeof options.data[b] !== undefined ? options.data[b] : ''; }); grunt.file.write(options.dest, content); }); grunt.registerTask('default', ['myTask']); 

过去我用过grunt-include-replace 。 很容易使用。 在你的grunt文件中,你将创build一个类似于这个的任务(例子来自官方的github回购):

 grunt.initConfig({ includereplace: { your_target: { options: { // Task-specific options go here. }, // Files to perform replacements and includes with src: '*.html', // Destination directory to copy files to dest: 'dist/' } } })