用Grunt将HTML替换为文件内容

3

我有一个生产版本的html,现在想要将我的(各个)模板编译并放置到生产版本的html文件中。

目前使用concat很好地构建了单个模板文件,但我想像下面这样处理代码:

<html>
    <head></head>
    <body>
        {{templates}}
    </body>
</html>

我需要先从已合并的模板文件中提取源代码, 然后将{{templates}}替换为它。我找到了许多grunt插件可以进行替换,但似乎没有一个插件能够允许我

1个回答

3
我最终写了一个多任务处理它的程序:
grunt.registerMultiTask('integrateTemplate', 'Integrates compiled templates into html file', function () {
    var data = this.data,
        path = require('path'),
        src = grunt.file.read(data.src),
        dest = grunt.template.process(data.dest),
        templates = grunt.file.read(data.compiledTemplate),
        out;

    out = src.replace(/\{\{templates\}\}/g, templates);

    grunt.file.write(dest, out);
    grunt.log.writeln('Template integrated');

});

prod_template.html看起来是这个样子:

<html>
    <head>
    </head>
    <body>
         {{templates}}
    </body>
</html>

接着,我只需要这样调用它:

integrateTemplate: {
  main: {
    compiledTemplate: '<%= templates.main.dest %>', // Compiled template src
    src: 'prod_template.html',
    dest: 'index.html'
  }
}

不过,如果有更好的建议(我相信一定会有),我很乐意听取。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接