Handlebars 4.0.2应该包含哪些源文件?

时间:2015-09-16 14:46:30

标签: javascript handlebars.js

我刚刚开始使用Handlebars.js,我已经对HTML中应包含的内容感到困惑。

我设置了一个最小的helloworl HTML文件,如下所示:

<html>
<body>
  <script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
      <h1>{{title}}</h1>
      <div class="body">
        {{body}}
      </div>
    </div>
  </script>

  <script src="bower_components/jquery/dist/jquery.js"></script>
  <script src="bower_components/handlebars/handlebars.js"></script>
  <script src="bower_components/handlebars/handlebars.runtime.js"></script>
  <script type="text/javascript">
  var source   = $("#entry-template").html();
  var template = Handlebars.compile(source);
  var context = {title: "My New Post", body: "This is my first post!"};
  var html    = template(context);
  document.write(html);
  </script>
</body>
</html>

我收到以下错误:

[Error] TypeError: undefined is not a function (evaluating 'Handlebars.compile(source)')
global code (index.html, line 17)

此最小示例应包含哪些其他依赖项?

使用的版本:

  • jQuery 2.1.4
  • 把手4.0.2

1 个答案:

答案 0 :(得分:0)

  1. 您对bower_components/handlebars/handlebars.runtime.js的来电会覆盖bower_components/handlebars/handlebars.js设置的内容。

  2. 使用handlebars.runtime.js表示您的模板已经编译,因此您获得的Handlebars对象不包含compile函数。

  3. 删除<script src="bower_components/handlebars/handlebars.runtime.js"></script>,你应该好好去:http://jsfiddle.net/nikoshr/dr3gwh7u/

    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/handlebars/handlebars.js"></script>
    
    <script type="text/javascript">
        var source   = $("#entry-template").html();
        var template = Handlebars.compile(source);
        var context = {title: "My New Post", body: "This is my first post!"};
        var html    = template(context);
        $('body').append(html)
    </script>