Java HTML Templating with Handlebars and Undertow

Previously on Handling Content Types with Undertow we showed how to send a simple HTML response. That is a little too basic for our use case. However, JSP, JSF, Spring MVC... all seem like they have a bit of learning curve. All we really need is to pass an object to a template and render some HTML, nothing fancy. Let's take this a step further and follow the node / express approach of simply plugging in a HTML templating engine. Enter Handlebars, perfect, fairly simple syntax added to plain HTML anyone should be able to pick this up immediately (Yes MVC frameworks can use this also but do we need a framework for what a single class can do?). It also convienetly has ports in many languages. This means we can use the same templates client side (javascript) and server side if we want.

HTML Templating Utility

This is a rare case where we decided to make a simple abstraction hiding the underlying jknack handlebars implementation. Since it only really needs a few methods we can hide the implementation and easily swap it out later. Notice how we have a few config options. When we are running locally we want handlebars templates to be compiled on the fly and NOT cached. We also utilize HTML compression for all of the HTML specific methods. We also offer some non HTML templating methods. Sometimes it might make sense to abuse a HTML templating library to solve a similair problem.

These examples are better to clone the repo and run locally. The HTML compression will smash everything on one line. The final example includes all CSS / JS from bootstrap using the public CDN. To take this a step further you can integrate with webpack and npm to manage your javascript and assets. If you are not a strong HTML / CSS developer consider using a site template to make your website stand out.