Vatsan28
Vatsan28

Reputation: 41

Handlebar template is not able to read the data passed

I am new to handlebar and am stuck at rendering a template via a handlebar script. Below is the code. The output doesn't contain the object attribute that i pass to the template. Please help!

    <script   src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js">  </script>
    <script>
    var context = { "name" : "XYZ", "occupation" : "developer" };

    var templateScript = $('#handlebars-demo').html();
    var theTemplate = Handlebars.compile(templateScript);
    var html = theTemplate({name: "XYZ",occupation: "developer"});
    console.log(html);
    $(document.body).append(html);
</script>
<script id="handlebars-demo" type="text/x-handlebars-template">
<div>
    My name is {{name}}. I am a {{occupation}}. // This just just renders My name is . I am a .
</div>

Upvotes: 1

Views: 1778

Answers (2)

garvit agrawal
garvit agrawal

Reputation: 61

I was having the same problem, when using handlebar with node js.

The problem is when you create a handlebar template, it will pre-compile your script with the server-side compiler using it's context (response from the server). So the templateScript variable which doesn't have name and occupation yet in the context, will look something like this :

<div>
    My name is . I am a .
</div>

There are a couple of solution to avoid this:

  • add \{{ to escape the expression
<script id="handlebars-demo" type="text/x-handlebars-template">
    <div>
        My name is \{{name}}. I am a \{{occupation}}.
    </div>
</script>
  • pre-compile your client-side script separately.

For more information, checkout the below link: Node.js with Handlebars.js on server and client

Upvotes: 5

Rafalsonn
Rafalsonn

Reputation: 440

Try {{context.name}} and {{context.occupation}}

Upvotes: 1

Related Questions