allegro / handlebars-spring-boot-starter

Spring Boot auto-configuration for Handlebars
Apache License 2.0
108 stars 26 forks source link

How to Create a Custom Helper #16

Closed dadepo closed 8 years ago

dadepo commented 8 years ago

Hi. trying to create a custom helper but having little success with it. Here is the version of my setup

spring boot: 1.3.1.RELEASE handlebars-spring-boot-starter: 0.2.11 Not manually defining any handlebar related bean in the context.

So far what I have done based on the mention of @HandlebarsHelper in the readme was to create a class exactly as mentioned in the read me, annotated it with @HandlebarsHelper and later with Spring @Component.

So I have:

@Component
@HandlebarsHelper
class CustomHelper {

    public CustomHelper() {
    }

    public static CharSequence greet() {
        return "hello world";
    }
}

and in the .hbs file I have:

say {{greet}}

But when I visit the page, the following stack trace occurs:

nack.handlebars.HandlebarsException: classpath:website/aboutus.hbs:9:21: java.lang.IllegalStateException: could not execute helper: greet()
    classpath:website/aboutus.hbs:9:21] with root cause

java.lang.IllegalAccessException: Class com.github.jknack.handlebars.helper.MethodHelper can not access a member of class org.oruko.dictionary.website.helpers.CustomHelper with modifiers "public static"
        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102) ~[na:1.8.0_66]
        at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296) ~[na:1.8.0_66]
        at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288) ~[na:1.8.0_66]
        at java.lang.reflect.Method.invoke(Method.java:490) ~[na:1.8.0_66]
        at com.github.jknack.handlebars.helper.MethodHelper.apply(MethodHelper.java:79) ~[handlebars-4.0.3.jar!/:na]

Looks like things are going sideways at the point of reflection?

Question is, is this due to going about registering custom helpers the wrong way? or I just stumbled upon a bug?

If it is the former...it would be appreciated if you can help with clarifying the correct step to getting a custom helper registered. Thanks.

plesiecki commented 8 years ago

The readme didn't mention @Component annotation and static modifiers. You can also try making your CustomHelper class as public.

dadepo commented 8 years ago

Making the class public was the missing piece! Thanks!