Java HTML Templating With Handlebars and Undertow
Are you a Java programmer who wants to make a website? Good news! With Handlebars, you can create a site designed with the Java programming language.
Join the DZone community and get the full member experience.
Join For FreeResearching how to create a website in Java can be a daunting task. A few Google searches and you end up with tons of libraries and strong opinions. JSP, JSF, Spring MVC, GWT, Vaadin and many more. All of them seem like they have quite a 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 an HTML templating engine. Enter Handlebars - a perfect, fairly simple syntax added to plain HTML anyone should be able to pick up immediately (Yes, MVC frameworks can use this also, but do we need a framework for what a single class can do?). It also conveniently 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 an HTML templating library to solve a similar problem.
public class Templating {
private static final Logger log = LoggerFactory.getLogger(Templating.class);
// Once again using static for convenience use your own DI method.
private static final Templating DEFAULT;
static {
Templating.Builder builder =
new Templating.Builder()
.withHelper("dateFormat", TemplateHelpers::dateFormat)
.withHelper("md", new MarkdownHelper())
.withHelper(AssignHelper.NAME, AssignHelper.INSTANCE)
.register(HumanizeHelper::register);
// Don't cache locally, makes development annoying
if (Env.LOCAL != Env.get()) {
builder.withCaching()
.withResourceLoaders();
} else {
String root = AssetsConfig.assetsRoot();
builder.withLocalResourceLoaders(root);
}
DEFAULT = builder.build();
}
public static Templating instance() {
return DEFAULT;
}
private final Handlebars handlebars;
private final HtmlCompressor compressor = new HtmlCompressor();
Templating(Handlebars handlebars) {
this.handlebars = handlebars;
}
public String renderHtmlTemplate(String templateName, Object data) {
String response = renderTemplate(templateName, data);
return compressor.compress(response);
}
public String renderTemplate(String templateName, Object data) {
Template template;
try {
template = handlebars.compile(templateName);
} catch (IOException e) {
throw new RuntimeException(e);
}
return render(template, data);
}
public String renderRawHtmlTemplate(String rawTemplate, Object data) {
String response = renderRawTemplate(rawTemplate, data);
return compressor.compress(response);
}
public String renderRawTemplate(String rawTemplate, Object data) {
Template template;
try {
template = handlebars.compileInline(rawTemplate);
} catch (IOException e) {
throw new RuntimeException(e);
}
return render(template, data);
}
private String render(Template template, Object data) {
try {
// Can't currently get the jackson module working not sure why.
Map<String, Object> jsonMap = Json.serializer().mapFromJson(Json.serializer().toString(data));
if (log.isDebugEnabled()) {
log.debug("rendering template " + template.filename() + "\n" + Json.serializer().toPrettyString(jsonMap));
}
return template.apply(jsonMap);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static class Builder {
private final Handlebars handlebars = new Handlebars();
private final List<TemplateLoader> loaders = Lists.newArrayList();
public Builder() {
}
public Builder withResourceLoaders() {
log.debug("using resource loaders");
loaders.add(new ClassPathTemplateLoader());
loaders.add(new ClassPathTemplateLoader(TemplateLoader.DEFAULT_PREFIX, ".sql"));
return this;
}
public Builder withLocalResourceLoaders(String root) {
log.debug("using local loaders");
loaders.add(new FileTemplateLoader(root));
loaders.add(new FileTemplateLoader(root, ".sql"));
return this;
}
public Builder withCaching() {
log.debug("Using caching handlebars");
handlebars.with(new ConcurrentMapTemplateCache());
return this;
}
public <T> Builder withHelper(String helperName, Helper<T> helper) {
log.debug("using template helper {}" , helperName);
handlebars.registerHelper(helperName, helper);
return this;
}
public <T> Builder register(Consumer<Handlebars> consumer) {
log.debug("registering helpers");
consumer.accept(handlebars);
return this;
}
public Templating build() {
handlebars.with(loaders.toArray(new TemplateLoader[0]));
return new Templating(handlebars);
}
}
}
Undertow HTML Templating Sender
A few simple lines and we can now send HTML templates with Undertow.
default void sendRawHtmlTemplate(HttpServerExchange exchange, String rawTemplate, Object data) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
exchange.getResponseSender().send(Templating.instance().renderRawHtmlTemplate(rawTemplate, data));
}
default void sendHtmlTemplate(HttpServerExchange exchange, String templateName, Object data) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
exchange.getResponseSender().send(Templating.instance().renderHtmlTemplate(templateName, data));
}
Undertow HTML Templating Server
Routes for the Handlers below.
private static final HttpHandler ROUTES = new RoutingHandler()
.get("/messageRawTemplate", HandlebarsHandlers::messageRawTemplate)
.get("/messagesRawTemplate", HandlebarsHandlers::messagesRawTemplate)
.get("/messagesTemplate", HandlebarsHandlers::messagesTemplate)
;
public static void main(String[] args) {
SimpleServer server = SimpleServer.simpleServer(ROUTES);
server.start();
}
Undertow HTML Templating Handlers
Simple Raw Handlebars HTML Template
Simple inline Java Handlebars template with variable substitution.
private static final String messageTemplate = "<p>hello {{message}}</p>";
public static void messageRawTemplate(HttpServerExchange exchange) {
String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
Map<String, Object> data = Maps.newHashMap();
data.put("message", message);
Exchange.body().sendRawHtmlTemplate(exchange, messageTemplate, data);
}
curl localhost:8080/messageRawTemplate?message=StubbornJava
<p>hello StubbornJava</p>
Iterating Raw Handlebars HTML Template
Simple inline Java Handlebars template with iteration substitution.
private static final String messagesTemplate = "{{#each messages}}<p>Hello {{.}}</p>{{/each}}";
public static void messagesRawTemplate(HttpServerExchange exchange) {
String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5);
List<String> messages = Lists.newArrayList();
for (int i = 0; i < num; i++) {
messages.add(message + " " + i);
}
Map<String, Object> data = Maps.newHashMap();
data.put("messages", messages);
Exchange.body().sendRawHtmlTemplate(exchange, messagesTemplate, data);
}
curl 'localhost:8080/messagesRawTemplate?message=StubbornJava&num=3'
<p>Hello StubbornJava 0</p><p>Hello StubbornJava 1</p><p>Hello StubbornJava 2</p>
Handlebars HTML Template With CSS
Java Handlebars template from resource files with layout, includes, and iteration. Now, this is starting to look like a real website. Find the templates here.
public static void messagesTemplate(HttpServerExchange exchange) {
String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5);
List<String> messages = Lists.newArrayList();
for (int i = 0; i < num; i++) {
messages.add(message + " " + i);
}
Map<String, Object> data = Maps.newHashMap();
data.put("messages", messages);
Exchange.body().sendHtmlTemplate(exchange, "examples/handlebars/messages", data);
}
curl 'localhost:8080/messagesTemplate?message=StubbornJava&num=3'
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/> <title>Messages Demo</title> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand logo" href="/">Demo</a> </div> </div> </nav> <div class="container"> <p>Hello StubbornJava 0</p><p>Hello StubbornJava 1</p><p>Hello StubbornJava 2</p> </div> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>
These examples are better to clone from 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. In later examples, we can get into using Webpack to manage HTML/CSS/JS.
Published at DZone with permission of Bill O'Neil. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments