dzm
dzm

Reputation: 23564

Handlebars.js not replacing tags

I'm using Handlebars.js (or trying to) and even with a simple example, it's not replacing the actual tags with the data.

Here's what I have:

    <script id="template" type="text/x-handlebars-template">
     <div>Test Template</div>
     <p>Name: {{name}}</p>
    </script>

    <div id="template-preview"></div>

 <script>
 var source   = $("#template").html();
 var template = Handlebars.compile(source);
 var data = { name : 'first name'};
 $("#template-preview").html(template(data));
</script>

I don't get any errors and it displays the template within template-preview, but the {{name}} is empty. Any ideas if I'm missing something here?

Thank you!

Upvotes: 3

Views: 1872

Answers (2)

Maljay
Maljay

Reputation: 11

You have to escape at least one of the curly brackets; otherwise, server-side view processing would attempt to make the replacements, thus returning {{name}} as an empty string. Your code should be like:

<!doctype html>

<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
  <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
  <script id="template" type="text/x-handlebars-template">
    <div>Test Template</div>
     <p>Name: \{{name}}</p>
     </script>
  <div id="template-preview"></div>

  <script>
    var source = $("#template").html();
    var template = Handlebars.compile(source);
    var data = {
      name: 'Michael'
    };
    $("#template-preview").html(template(data));
  </script>
</body>

</html>

Upvotes: 1

Foo Bar
Foo Bar

Reputation: 281

This works for me (tested with Chrome). Which version of handlebars you're using?

<!doctype html>
<head>
</head>
<body>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
     <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
     <script id="template" type="text/x-handlebars-template">
     <div>Test Template</div>
     <p>Name: {{name}}</p>
     </script>
     <div id="template-preview"></div>

     <script>
        var source   = $("#template").html();
        var template = Handlebars.compile(source);
        var data = { name : 'Michael'};
        $("#template-preview").html(template(data));
     </script>
</body>
</html>

Upvotes: 0

Related Questions