【问题标题】:NPM mustache-render create multiple HTMLs with single template and multiple JSONsNPM mustache-render 使用单个模板和多个 JSON 创建多个 HTML
【发布时间】:2017-09-07 16:05:05
【问题描述】:

我正在使用 npm grunt-mustache-render (https://www.npmjs.com/package/grunt-mustache-render) 来生成 HTML 文件。我可以使用 1 个 json 和 1 个模板创建 html。现在,我正在尝试基于 1 个模板和多个 json 文件创建多个 HTML 文件。我不想一一明确命名所有的json。相反,我想指定所有 json 文件的路径,模板的路径,然后是 dist 路径,以便它根据 json 文件名生成 HTML 文件。

这是我的繁重任务:

mustache_render: {
      json_data: {
        files: [
          {expand: true,
           src: 'content/*.json',
           template: 'templates/menu-content.mustache',
           dest: 'publish/'}
        ]
      }
    }

但它不会创建 HTML 文件。相反,它会创建多个包含 HTML 代码的 .json 文件。另请注意,它会在 publish/content/ 文件夹中创建文件,而不是在我想要的位置 publish/ 。下面是输出的样子:

Output publish/content/page-one.json:
>> 2-key object into templates/menu-content.mustache from content/page-one.json
Output publish/content/page-three.json:
>> 5-key object into templates/menu-content.mustache from content/page-three.json
Output publish/content/page-two.json:
>> 5-key object into templates/menu-content.mustache from content/page-two.json

我做错了什么?甚至可以用 grunt-mustache-render 做我正在尝试的事情吗?

TIA。

【问题讨论】:

    标签: javascript json node.js gruntjs mustache


    【解决方案1】:

    这可以通过基于.json 文件动态生成mustache_render 任务的配置来实现。

    尝试如下配置您的Gruntfile.js

    Gruntfile.js

    module.exports = function (grunt) {
    
      'use strict';
    
      grunt.initConfig({
        mustache_render: {} // Intentionally empty, will be auto generated.
      });
    
      /**
       * Helper function auto generates the configuration object for 
       * the mustache_render Task based on the .json files found.
       */
      function generateHtml() {
        var config = {},
          pathsToJson = 'content/*.json';
    
        grunt.file.expand(pathsToJson).forEach(function (filePath, index) {
          // .html filename based on .json filename.
          var htmlFileName = filePath.split('/').pop().split('.')[0] + '.html';
    
          config[index] = {
            files : [{
              data: filePath,
              template: 'templates/menu-content.mustache',
              dest: 'publish/' + htmlFileName
            }]
          }
        });
    
        // Add the generated config object to mustache_render Task then run it.
        grunt.config('mustache_render', config);
        grunt.task.run(['mustache_render']);
      }
    
      grunt.loadNpmTasks('grunt-mustache-render');
      grunt.registerTask('buildHtml', generateHtml);
      grunt.registerTask('default', ['buildHtml']);
    };
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 2013-08-06
      • 2019-04-26
      • 2019-06-21
      • 2018-05-04
      • 1970-01-01
      • 2021-08-10
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多