Mustache 模板 - 不显示且不抛出错误的基本示例

Mustache templating - Basic example not displaying and not throwing errors

我一直在寻找使用 Mustache 模板的简单基本示例,其中 Mustache 标记和模板保留在 HTML 文档中(关注点分离)。

这是我所在的位置:

<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
</head>
<body>
  <div class="container">
    <h2>Here is a person</h2>
    <template id="theTemplate">
      {{name}}
    </template>
  </div>

  <script>
    $(function() {
      template = $('#theTemplate').html();
      data = {
        name: 'billy'
      };
      Mustache.render(template, data);
    });
  </script>
</body>
</html>

没有抛出任何错误,但它不工作!

Mustache.render returns 一个字符串,它是模板和所提供对象中数据的合并。它不会对该字符串执行任何其他操作,因此如果您想更新 DOM,您仍然需要手动执行此操作。当您使用 jQuery 时,您可以使用 append() 来做到这一点:

$('h2').append(Mustache.render(template, data));

但是,将整个 h2 文本值包含在模板中会更有意义,至少使其值得使用:

$(function() {
  template = $('#theTemplate').html();
  data = { name: 'billy' };
  $('h2').text(Mustache.render(template, data));
});
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<div class="container">
  <h2></h2>
  <template id="theTemplate">
    Here is a person named {{name}}
  </template>
</div>