I am using handlebars template. I have stumbled across a strange problem. Following code is not passing context to compiled handlebars template when used on browser but strange thing is that same code works fine in jsfiddle ! https://jsfiddle.net/5pnfrjwa/
Here is my code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{{> navbar this }}
<div id="render_here">
first
</div>
<div id="render_here_again">
second
</div>
<script id="first-template" type="text/x-handlebars-template">
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :{{title1}}</h4>
<h4 style="color:blue">body1 :{{body1}}</h4>
<h4 style="color:blue">context : {{context}}</h4>
</div>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js"></script>
<script>
$(document).ready(function() {
var source = $("#first-template").html();
var template = Handlebars.compile(source);
var context
// = "test 1"
= {
title1: "hello",
body1: "body1"
}
var el_html = template(context);
console.log("*** This is source : " + source);
console.log("*** This is template : " + template);
console.log("*** This is template(context) : " + el_html)
console.log(" data is : " + context.title1)
// $(document.body).append(el_html);
// $("#render_here").html(el_html);
// $("#render_here_again").html(el_html);
// document.getElementById('render_here_again').innerHTML = template(context);
$("#render_here_again").html(el_html)
});
</script>
</body>
</html>
I displayed source to console and here is the output
*** This is source :
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :</h4>
<h4 style="color:blue">body1 :</h4>
<h4 style="color:blue">context : </h4>
</div>
If same is displayed on jsfiddle, its as below:
*** This is source :
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :{{title1}}</h4>
<h4 style="color:blue">body1 :{{body1}}</h4>
<h4 style="color:blue">context : {{context}}</h4>
</div>
It seems variable name is coming in the source in double curly brackets on jsfiddle but its not coming on my locale machine. Any idea why this behaves differently on browser and jsfiddle. I tried it with chrome and Mozilla but facing same issue with both. I am using nodejs and expressjs at server side.
Edit one It seems I might have identified the issue but I am still searching for solution. This is happening when I am rendering this pages from express 4 server. If I open simple html file with above code, its working fine.