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.HandlebarsViewsRenderer
class and its inner propertyhandlebars
. The good news is that this property has aprotected
scope - it means that we can create another bean in the same package in our source code and we can injectHandlebarsViewsRenderer
and accessHandlebarsViewsRenderer.handlebars
field. 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.handlebars
object.2. Create
io.micronaut.views.handlebars.HandlebarsCustomConfig
classsrc/main/java/io/micronaut/views/handlebars/HandlebarsCustomConfig.java
Here in this class I have created a simple
HelperSource
class that exposes a single helper called{{now}}
.3. Load
HandlebarsCustomConfig
beanThis 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
@Replaces
alternativeYou can use Micronauts
@Replaces
annotation to replaceHandlebarsViewsRenderer
with a custom implementation.It has a few advantages comparing to the previous solution:
io.micronaut.views.handlebars
package.main
method to initialize it properly.