I am new to Handlebars JS and just trying to understand them. I am trying to implement handlebars on a data that contains array of hashes. Here is my script:-
RequestBody
Nothing is displayed on the output
How to use the handlebars template to access an array of hashes. Ex- variable <div id="test"></div>
<script id="template" type="text/x-handlebars-template">
<h1>{{title}}</h1>
<h2>{{body}}</h2>
</script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<script>
$(document).ready(function (){
var source = $("#template").html();
var template = Handlebars.compile(source);
var context = [{title: "ABC",body: "DEF"},{title: "GHI",body:"JKL"}];
console.log(context);
var ht = template(context);
console.log(ht);
$("#test").html(ht);
});
</script>
in the above script.
Can we use handlebars only on hashes ?
Can anyone please explain me this.
Thanks
答案 0 :(得分:0)
You can iterate through collection using {{#each}} helper. In your case it would be something like this:
event
Of course we can use it only on hashes - just try. You might find reading this useful: http://handlebarsjs.com/builtin_helpers.html
I hope your script tag doesn't look like in your post and it actually doesn't lack of "http" part
{{#each this}}
<h1>{{title}}</h1>
<h2>{{body}}</h2>
{{/each}}