I am wondering where (or how) should I declare helpers for Handlebars in my Micronaut project?
I have tried following approach:
public class Application {
public static void main(String[] args) {
Micronaut.run(Application.class);
Handlebars handlebars = new Handlebars();
handlebars.registerHelpers(HelperSource.class);
}
}
This had no effect. How can I register Handlebars helpers in a Micronaut application?
There is no configuration to register Handlebars helpers in current Micronaut 1.0 GA release. However, there is a simple workaround you can apply to overcome this limitation. To make helpers registration possible you have to access
io.micronaut.views.handlebars.HandlebarsViewsRendererclass and its inner propertyhandlebars. The good news is that this property has aprotectedscope - it means that we can create another bean in the same package in our source code and we can injectHandlebarsViewsRendererand accessHandlebarsViewsRenderer.handlebarsfield. Having an access to this field we can executehandlebars.registerHelpers(...)method.You can simply follow these steps:
1. Add Handlebars.java dependency
It is important to add it in the compile scope, because runtime scope won't allow you to access
HandlebarsViewsRenderer.handlebarsobject.2. Create
io.micronaut.views.handlebars.HandlebarsCustomConfigclasssrc/main/java/io/micronaut/views/handlebars/HandlebarsCustomConfig.java
Here in this class I have created a simple
HelperSourceclass that exposes a single helper called{{now}}.3. Load
HandlebarsCustomConfigbeanThis step is crucial. We need to load the bean, otherwise Micronaut would not create an instance of it and our helpers registration would not take place.
4. Create a view
src/main/resources/views/home.hbs
5. Run application and see the results
@ReplacesalternativeYou can use Micronauts
@Replacesannotation to replaceHandlebarsViewsRendererwith a custom implementation.It has a few advantages comparing to the previous solution:
io.micronaut.views.handlebarspackage.mainmethod to initialize it properly.