Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use json with Handlebars.java

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?

like image 633
gopalanj Avatar asked Dec 19 '22 13:12

gopalanj


1 Answers

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));
    }
}
like image 59
gopalanj Avatar answered Jan 10 '23 23:01

gopalanj