JsonNodeValueResolver & passing ObjectNodes to helper functions

33 views
Skip to first unread message

Lance Walton

unread,
Mar 7, 2019, 11:04:45 AM3/7/19
to handlebars.java
Hi.

I have the following Scala code:

import com.fasterxml.jackson.databind.{ JsonNode, ObjectMapper }
import com.github.jknack.handlebars.{ Context, Handlebars, JsonNodeValueResolver }

object Foo extends App {

class Helpers {
def notWorking(node: JsonNode): CharSequence = "hello"
def working(s: String): CharSequence = "Yay! " + s
}

private val handlebars = new Handlebars
handlebars.registerHelpers(new Helpers)

val data: JsonNode = new ObjectMapper().readTree("{ \"myField\": { \"myNestedField\": \"2\" } }")
val context: Context = Context
.newBuilder(data)
.resolver(JsonNodeValueResolver.INSTANCE)
.build

val template = "{{working myField.myNestedField}}"

println(handlebars.compileInline(template).apply(context))
}

This works fine & prints out "Yay! 2".

However, I changed the template to this:

val template = "{{notWorking myField}}"

& I'm hoping my notWorking helper function would be called with the JsonNode { "myNestedField": "2" }. However, I get an exception:

Exception in thread "main" com.github.jknack.handlebars.HandlebarsException: inline@175f056c:1:2: java.lang.IllegalArgumentException: argument type mismatch
inline@175f056c:1:2
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.github.jknack.handlebars.helper.MethodHelper.apply(MethodHelper.java:79)
at com.github.jknack.handlebars.internal.Variable.value(Variable.java:181)
at com.github.jknack.handlebars.internal.Variable.merge(Variable.java:160)
at com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:130)
at com.github.jknack.handlebars.internal.TemplateList.merge(TemplateList.java:95)
at com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:130)
at com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:118)
at com.github.jknack.handlebars.internal.ForwardingTemplate.apply(ForwardingTemplate.java:100)
...

If I change the notWorking parameter type to Any (Scala's equivalent of Object), the function gets called, & I can see that the type of the parameter is JsonNodeValueResolver$1, which looks to be a subclass of java.util.Map

Is this the expected behaviour? Should I just make my parameter type java.util.Map<String, JsonNode>?
Reply all
Reply to author
Forward
0 new messages