Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 224
dzm Avatar asked Feb 16 '26 18:02

dzm


1 Answers

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>
like image 103
Maljay Avatar answered Feb 18 '26 09:02

Maljay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!