Skip to content

Enable Helper Source to override Helper Name via Annotation #829

@carusology

Description

@carusology

Background

A helpful way to reduce registering each helper method individually and to avoid superfluous context objects in a helper method is to use the "helper source" paradigm described in the Handlebars.java blog. If you pass in a class or object to one of the HelperRegistry.registerHelpers() overloads, the argument will be scanned for public methods that return strings.

However, one of the restrictions is pretty strict in its implementation:

The method's name become the name of the helper

You can't override the name of the helper, and there's no easy way to override this behavior without completely replacing it. You can see the logic that extracts the helper name in the private DefaultHelperRegistry.registerDynamicHelper() method. You have to wrap or inherit from DefaultHelperRegistry and reimplement a decent amount of type-checking and reflection logic to add it in.

This kind of override is desirable as the naming convention of helper functions used by a given template library may not be consistent with java method naming conventions, or they may require a more verbose name to be self-describing in their functionality when they appear in templates (far away from their encapsulating class).

Proposal

We could add a new annotation, something like @HelperFn(), where we could pass in the name of the helper function as we want it to be used within Handlebars. If the method is annotated with it, great, we'll use the annotated name. If not, we'll use the current behavior.

Here's an example of what that might look like, where a helper function with the name of "home-url" would be registered that invokes this method.

public class UrlHelpers {

    @HelperFn("home-url")
    public String home() {
        return this.baseUrl + "/home"
    }

}

Is this something you'd accept if I were to submit a pull request? I'd be happy to implement it.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions