Discrepancy in variable lookup between Handlebars and Mustache
I ran into this difference between Handlebars and Mustache when running a loop. In Mustache the top level data is accessible in the same way as outside the loop. In Handlebars, the top level data is only accessible through the use of ../ (ie. {{../company.name}}. I was wondering if this is intended behaviour of Handlebars or a bug. If it is intended behaviour, the claim that 'Mustache templates are compatible with Handlebars' is not true in this case.
by brikkelt
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.rc.1/handlebars.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<div style="display: none;" class="template">
<ul>
{{#persons}}
<li><a href="{{company.url}}/about-us/">{{firstName}} {{lastName}}</a> ({{company.name}})</li>
{{/persons}}
</ul>
</div>
<h1>Handlebars output</h1>
<p>No implicit access to top level data (the company name is missing)</p>
<div class="handlebars">
</div>
<h1>Mustache output</h1>
<p>Implicit access to top level data.</p>
<div class="mustache">
</div>
CSS
.template {
display: none;
}
h1 {
margin: 1em 0 .25em 0;
font-weight: bold;
}
p {
margin: .25em 0;
}
JavaScript
var data = {
persons: [
{
firstName: "Yehuda",
lastName: "Katz"
},
{
firstName: "Leah",
lastName: "Silber"
},
{
firstName: "Peter",
lastName: "Wagenet"
}
],
company: {
name: "Tilde, Inc.",
url: "http://www.tilde.com"
}
};
var templateSource = jQuery(".template").html();
var handlebarsTemplate = Handlebars.compile(templateSource);
var mustacheTemplate = Mustache.compile(templateSource);
jQuery(".handlebars").html(handlebarsTemplate(data));
jQuery(".mustache").html(mustacheTemplate(data));