Get Even More Visitors To Your Blog, Upgrade To A Business Listing >> – How to use it as Server side Template Engine?

Tags: template

{{ }} - Mustache templates in Java

      is a server side Java Template engine like velocity, freemaker etc.. It follows the syntax of Mustache spec. The main goal of is to reuse the same templates at client side and server side. In this article we will see how to use along with Spring framework. I have used Spring Boot for the demonstration. Follow the below steps to setup and run the

Step 1:

Include the implementation in the pom.xml


As we are going to use JSON as the data to be rendered with handlebars template, we will include handlebars JSON helper in the class path.


Step 2:

Write handlebar template to render home page. Here, I divided the home page template into header and footer and included them as partials.

This is the sample template to demonstrate the Handlebars JAVA. This uses JSON to render.
{{>footer/footer address}}

The header template is given below.

Hi, This is {{title}} {{name}}

The footer template is given below.

The address is given below.




state :{{state}}

Step 3:

As we are using Spring Boot, I kept the templates under resources/templates folder. Load the templates from the calsspath.

TemplateLoader loader = new ClassPathTemplateLoader("/templates", ".hbs");
final Cache templateCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(1000).build();
setHandlebars(new Handlebars(loader).with((new GuavaTemplateCache(templateCache))));

Step 4:

Compile the template and apply the data to render.

Template template = this.getHandlebars().compile(templateName);
//Sample JSON to render the home template
String responseJson = "{\"title\":\"Mr.\",\"name\":\"ABC\",\"address\":{\"address1\":\"address1\",\"address2\":\"address2\",\"city\":\"XYZ\",\"state\":\"State1\"}}";
JsonNode jsonNode = new ObjectMapper().readValue(responseJson, JsonNode.class);
//get the compiled template
Template template = handlebarsDemoTemplateLoader.getTemplate("home");
//Apply the JSON data by passing the context

I included the above in org.smarttechie.controller.HandlebarsDemoController with the context path /demo and the request mapping to the controller is /home. Just run the org.smarttechie.HandlebarsjavaDemoApplication and send the request to  /demo/home to see the rendered home page handlebar template. The source code created for this example is available on GitHub. Download it and explore more about the handlebars java implementation.

Spring Boot Handlebars Java Demonstration

This post first appeared on Smart Techie | My Thoughts, My Work, My Ideas, please read the originial post: here

Share the post – How to use it as Server side Template Engine?


Subscribe to Smart Techie | My Thoughts, My Work, My Ideas

Get updates delivered right to your inbox!

Thank you for your subscription