Handlebars.java

Logic-less and semantic templates with Java


by Edgar Espina Theme by mattgraham

The Jackson module in Handlebars.java

In this section you will learn how to convert a value to JSON using the Jackson library and much more.

The Jackson 2.x module is available in Maven central
<dependency>
  <groupId>com.github.jknack</groupId>
  <artifactId>handlebars-jackson2</artifactId>
  <version>1.0.0</version>
</dependency>

The Jackson helper

The Jackson helper convert a JavaObject to JSON.

Registering the Jackson helper:
handlebars.registerHelper("json", JacksonHelper2.INSTANCE);
Registering the Jackson helper with a customObjectMapper:
ObjectMapper om = ...;
handlebars.registerHelper("json", new JacksonHelper2(om));
Using the JSON helper:
{{json this}}

Jackson Views

JSON views:
{{json this view="foo.MyFullyQualifiedClassName"}}
Alias for JSON views:
handlebars.registerHelper("json", new JacksonHelper2()
   .viewAlias("myView", foo.MyFullyQualifiedClassName.class);
...
{{json this view="myView"}}

Escaping HTML chars

You might want to setescapeHTMLif your JSON has HTML content.
{{json this escapeHTML=true}}

The JsonNodeValueResolver

The Jackson module has a custom ValueResolver that knows how to extract values from aJsonNodeobject.

Registering the JsonNodeValueResolver:
Context context = Context
  .newBuilder(model)
  .resolver(JsonNodeValueResolver.INSTANCE)
  .build();

Conclusion

As you see, Handlebars.java provides you a very nice integration with Jackson the most widely used JSON library for Java.

Want to contribute?

Thank you, for reading the Handlebars.java blog.