Handlebars (Java) Templates and Extensions are really powerful

I have recently moved a project from using Thymeleaf to using Handlebars.

Handlebars is a templating library (think mail merge for code if you are a non-developer).

Handlebars uses the {{ }} tags to surround items to be replaced.

{{{   }}} will not escape content provided.

{{ > path/to/file }}  Renders a template. You can supply named blocks that get substituted into that template.

By default the template uses whatever data that the template was bound to. Typically we bind nested Maps.

One of the principles of handlebars is that the templates should be logic free. This means that you are limited to {{#if }}, {{#unless }} and {{#each }} blocks.

#If will check the truthiness of a value. The intent is to include a block of template only if a certain item is present, say an optional middle name.

#unless is the inverse, it will only show the block if the condition is false. This is ideal for providing defaults for missing data.

Any logic above this must be handled by an extension method.

This is not as difficult as it sounds. With a little effort extension methods can be written to:

  • Invoke a template name specified in a variable.
  • Perform custom sorting of data acting as a custom loop over a supplied block.

By keeping the logic isolated it becomes independently testable and simplifies the templates.