1

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>

Vatsan28
  • 41
  • 1
  • 6

2 Answers2

5

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

1

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

Rafalsonn
  • 430
  • 7
  • 23
  • It still doesn't work. Is there something I need to with the config on my node app? Its a node app. Sorry, i should have mentioned that first. – Vatsan28 Jul 26 '16 at 20:49