I am trying to use handlebars.java to apply json data. I took the below example from https://github.com/jknack/handlebars.java where it was for handlebars.js and I expect the same will work in handlebars.java
public class TestHandlebars {
public static void main(String[] args) throws Exception {
String json = "{\"name\": \"world\"}";
Handlebars handlebars = new Handlebars();
handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
Context context = Context
.newBuilder(json)
.resolver(JsonNodeValueResolver.INSTANCE,
JavaBeanValueResolver.INSTANCE,
FieldValueResolver.INSTANCE,
MapValueResolver.INSTANCE,
MethodValueResolver.INSTANCE
)
.build();
Template template = handlebars.compileInline("Hello {{name}}!");
System.out.println(template.apply(context));
}
}
I am expecting the output as
Hello world!
whereas I am getting just
Hello !
What am I missing? I have seen the examples like with Jackson views with java model "Blog" at https://github.com/jknack/handlebars.java, but can't this be achieved without using java model objects for that json?
Just found out that passing the json as JsonNode object works.
public class TestHandlebars {
public static void main(String[] args) throws Exception {
String json = "{\"name\": \"world\"}";
JsonNode jsonNode = new ObjectMapper().readValue(json, JsonNode.class);
Handlebars handlebars = new Handlebars();
handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
Context context = Context
.newBuilder(jsonNode)
.resolver(JsonNodeValueResolver.INSTANCE,
JavaBeanValueResolver.INSTANCE,
FieldValueResolver.INSTANCE,
MapValueResolver.INSTANCE,
MethodValueResolver.INSTANCE
)
.build();
Template template = handlebars.compileInline("Hello {{name}}!");
System.out.println(template.apply(context));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With