Search code examples
javascripthandlebars.js

What source files should be included for Handlebars 4.0.2?


I'm just getting started with Handlebars.js and I'm already confused by what should be included in my HTML.

I set up a minimal helloworl HTML file that looks like:

<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>

and I get the following error:

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

What other dependency should be included for this minimal example to work?

Versions used:

  • jQuery 2.1.4
  • handlebars 4.0.2

Solution

    1. Your call to bower_components/handlebars/handlebars.runtime.js overwrites what bower_components/handlebars/handlebars.js sets up.

    2. Using handlebars.runtime.js implies that your templates are already compiled and thus the Handlebars object you get does not include a compile function.

    Remove <script src="bower_components/handlebars/handlebars.runtime.js"></script>and you should be good to go : 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>