Grunt mustache_render 无法正确呈现 HTML 文件

Grunt mustache_render won't render HTML file correctly

我正在使用 https://www.npmjs.com/package/grunt-mustache-render 使用布局文件和 json 文件渲染 HTML 文件。

这是 G运行t 任务:

mustache_render: {
      json_data: {
        files: [
          {
            data: 'output.json',
            template: 'test.mustache',
            dest: 'tmp/hello_json.html'
          }
        ]
      }
    }

输出 JSON 如下所示:

[
  {
    "name": "John Doe",
    "age": "30"
  },
  {
   "name": "Alex Len",
    "age": "27"
  },
  {
   "name": "Debbie John",
    "age": "36"
  }

]

test.mustache 看起来像这样:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Mustache Sample</title>
</head>
<body>
  <h2>Titles</h2>
  <ul id="talktitles">
    <script id="speakers-template" type="text/template">
    {{#options}}
      <li>{{{name}}}, {{{age}}}</li>
    {{/options}}
  </script>
  </ul>
</body>
</html>

当我 运行 g运行t 它创建了 tmp/hello_json.html 文件但没有填充值。它看起来像这样:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Mustache Sample</title>
</head>
<body>
  <h2>Titles</h2>
  <ul id="talktitles">
    <script id="speakers-template" type="text/template">
  </script>
  </ul>
</body>
</html>

我做错了什么?

您的 output.json 不符合模板。模板在 json 文件中等待 options 值,但没有这样的键。

正确的输出json应该是这样的:

{
  options: [{
      "name": "John Doe",
      "age": "30"
    }, {
      "name": "Alex Len",
      "age": "27"
    }, {
     "name": "Debbie John",
     "age": "36"
    }]
}

加法

您还可以使用 . 引用 json 文件的根目录 所以你可以把你的模板部分改成这个

    {{#.}}
      <li>{{{name}}}, {{{age}}}</li>
    {{/.}}