Handlebars.java is a Java implementation of Mustache. You can use Handlebars.java in any Java environment, but especially in web applications that make heavy use of JavaScript.
Beside Handlebars.java is a multi-purpose template engine, one of the reason that makes Handlebars.java special, is that you can use the same template engine in the browser.
These are the most used implementations of Mustache for JavaScriptOf course that Handlebars.js is what makes more sense to use, but you can also choose between any other existing implementations of Mustache.
The best way of getting started is by reading the Mustache documentation. You will find it very easy to follow and understand.
Then you might want to read the Handlebars.js documentation for a better understanding of how Handlebars.js extends Mustache through the use of helpers.
Handlebars handlebars = new Handlebars();
Template template = handlebars.compileInline("Hello {{this}}!");
System.out.println(template.apply("Handlebars.java"));
Print out:
Hello Handlebars.java!
Mustache is very simply template engine with just a few constructions. In the example above, "{{this}}"
get resolved to "Handlebars.java"
.
The with
helper let you switch/change the current context to something else.
For example:
Model:
{
title: {
story: {
name: "Handlebars.java rocks!"
}
}
}
<h1>{{title}}</h1>
{{#with story}}
<span>{{name}}</span>
{{/with}}
<h1>{{title}}</h1>
{{#story}}
<span>{{name}}</span>
{{/story}}
The each
helper let you iterate over collections, arrays and objects.
For example:
Model:
{
blogs: [
title: {
story: {
name: "Handlebars.java rocks!"
}
}
]
}
{{#each blogs}}
<h1>{{title}}</h1>
{{#with story}}
<span>{{name}}</span>
{{/with}}
{{/each}}
{{#blogs}}
<h1>{{title}}</h1>
{{#story}}
<span>{{name}}</span>
{{/story}}
{{/blogs}}
The if
helper evaluate a context value as true
. For example:
Is Active?
{{#if active}}
Yes
{{/if}}
Is Active?
{{#active}}
Yes
{{/active}}
You can add an else
branch using the else
keyword or the ^
character:
Is Active?
{{#if active}}
Yes
{{else}}
No
{{/if}}
Is Active?
{{#if active}}
Yes
{{^}}
No
{{/if}}
The unless
helper evaluate a context value as false
. For example:
Is Active?
{{#unless active}}
No
{{/unless}}
Is Active?
{{^active}}
No
{{/active}}
Thank you, for reading the Handlebars.java blog.