Reputation: 41
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
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:
\{{
to escape the expression <script id="handlebars-demo" type="text/x-handlebars-template"> <div> My name is \{{name}}. I am a \{{occupation}}. </div> </script>
For more information, checkout the below link: Node.js with Handlebars.js on server and client
Upvotes: 5