Blocks
General Syntax of block helpers:
- Helpers are called as block helper by prefixing the name with
#. - Block helpers have an inner template block.
- Block helpers can have an alternative or otherwise template block.
{{#helperName arguments.. hashs..}} inner block {{/helperName}}
{{#helperName arguments.. hashs..}}
true block
{{else}}
otherwise block
{{/helperName}}
#if
The if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
When applying the input below to the template:
{
"author": true,
"firstName": "Yehuda",
"lastName": "Katz"
}
It will produce the result:
<div class="entry">
<h1>Yehuda Katz</h1>
</div>
If the input is an empty JSONObject {}, then author will become undefined and if condition fails, resulting in the output as follows:
<div class="entry"></div>
When using a block expression, you can specify a template section to run if the expression returns a falsy value. The section, marked by else is called an "else section".
#unless
You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value.
If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.
#each
You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.
When used with this context:
{
"people": ["Yehuda Katz", "Alan Johnson", "Charles Jolley"]
}
it will result in:
<ul class="people_list">
<li>Yehuda Katz</li>
<li>Alan Johnson</li>
<li>Charles Jolley</li>
</ul>
You can use the this expression in any context to reference the current context.
You can optionally provide an else section which will display only when the list is empty.
When looping through items in each, you can optionally reference the current loop index via {{@index}}.
Additionally for object iteration, {{@key}} references the current key name:
The first and last steps of iteration are noted via the @first and @last variables when iterating over an array.
Nested each blocks may access the iteration variables via depth-based paths. To access the parent index, for example, {{@../index}} can be used.
#with
The with-helper allows you to change the evaluation context for the inner part of the template.
When used with this context:
{
"person": {
"firstname": "Yehuda",
"lastname": "Katz"
}
}
it will result in:
Yehuda Katz
#block
Template inheritance can be done with block/partial syntax.
Example:
base.hbs
home.hbs
So the output would be:
<h1>Title</h1>
<p>Home page</p>
<span>Powered by Handlebars.java</span>
#partial
A partial is a template that can be included into another template. You can see again the explanation of it in Handlebar - Partial section.