Block expressions allow you to define helpers that will invoke
a section of your template with a different context than the
current. These block helpers are identified by a #
preceeding
the helper name and require a matching closing mustache, /
, of the
same name.
Let's consider a helper that will generate an HTML list:
{{#list people}}{{firstName}} {{lastName}}{{/list}}
If we have the following context:
{
people: [
{firstName: "Yehuda", lastName: "Katz"},
{firstName: "Carl", lastName: "Lerche"},
{firstName: "Alan", lastName: "Johnson"}
]
}
we would create a helper named list
to generate our
HTML list. The helper receives the people
as its
first parameter, and an options hash as its second parameter.
The options hash contains a property named fn
,
which you can invoke with a context just as you would invoke a
normal Handlebars template.
Handlebars.registerHelper('list', function(items, options) {
var out = "<ul>";
for(var i=0, l=items.length; i<l; i++) {
out = out + "<li>" + options.fn(items[i]) + "</li>";
}
return out + "</ul>";
});
When executed, the template will render:
<ul>
<li>Yehuda Katz</li>
<li>Carl Lerche</li>
<li>Alan Johnson</li>
</ul>
Block helpers have more features, such as the ability to create an
else
section (used, for instance, by the built-in if
helper).
Since the contents of a block helper are escaped when you call
options.fn(context)
, Handlebars does not escape
the results of a block helper. If it did, inner content would
be double-escaped!
Learn More: Block Helpers