Reputation: 3869
I'm trying to use handlebars. It worked pefectly until I used the each function. The function works fine but it seems like it references everything to the parameters it takes. Therefore I cannot reach the object I want. I think a bit of code will be clearer anyway.
<div id="myDiv"></div>
<script type="text/x-handlebars-template" id="handlebar">
{{#each items}}
<p>{{this.name}} {{this.surname}}</p>
<p>{{somethingInTheGeneralContext}}</p>
{{/each}}
</script>
<script>
$( document ).ready(function() {
var source = $("#handlebar").html();
var template = Handlebars.compile(source);
var context = {
items: [
{
name:"Paul",
surname:"Buchon"
},
{
name:"Pierre",
surname:"Bino"
},
{
name:"Jean",
surname:"Duflou"
}
],
somethingInTheGeneralContext: "It works !"
};
var html = template(context);
$("#myDiv").html(html);
});
</script>
This prints :
Paul Buchon
Pierre Bino
Jean Duflou
And my somethingInTheGeneralContext is lost somewhere... Any idea how I can fix it ? Thanks!
Upvotes: 1
Views: 950
Reputation: 46657
I believe you can use {{../param}}
to break out of the each context and go back to the parent level, where somethingInTheGeneralContext
exists:
<script type="text/x-handlebars-template" id="handlebar">
{{#each items}}
<p>{{this.name}} {{this.surname}}</p>
<p>{{../somethingInTheGeneralContext}}</p>
{{/each}}
</script>
Upvotes: 4