gop*_*anj 1 java handlebars.js
我正在尝试使用handlebars.java来应用json数据.我从https://github.com/jknack/handlebars.java中获取了以下示例,其中是handlebars.js,我希望它在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));
}
}
Run Code Online (Sandbox Code Playgroud)
我期待输出为
你好,世界!
而我正好
你好 !
我错过了什么?我在https://github.com/jknack/handlebars.java上看过像Jackson模型"博客"的杰克逊观点的例子,但如果不使用json的java模型对象,这不可能实现吗?
刚发现传递json作为JsonNode对象起作用.
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));
}
}
Run Code Online (Sandbox Code Playgroud)