javascript - Grunt Mustache_render 无法正确渲染 HTML 文件

标签 javascript gruntjs mustache

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

这是 Grunt 任务:

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>

当我运行 grunt 时,它创建了 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>
    {{/.}}

关于javascript - Grunt Mustache_render 无法正确渲染 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789799/

相关文章:

javascript - 如何使用 mustache js 模板引擎访问嵌套对象

javascript - 仅在 AngularJS 中显示某些项目

node.js - 通过 Grunt 运行 Node 应用程序

angularjs - 如何将默认端点添加到 Angular $http 请求之前?

angularjs - 无法从 Grunt 服务器运行的 Node + AngularJS 应用程序中读取环境变量

java - Java 中的 Mustache 类型的字符串替换

mustache - PHP mustache 。隐式迭代器 : How to get key of current value(numeric php array)

javascript - 使用 facebook 图形 API 在 facebook 上通过 URL 发布视频?

javascript - 在第一次加载时更快地加载 javascript

javascript - Chrome/Firefox 中的 Ruby 时间转 JavaScript 日期