public class HandlebarsModule extends ConfigurableModule<HandlebarsModule.Config>
To use it one has to register the module and then render Template
instances.
Instances of Template
can be created using one of the
Template.handlebarsTemplate(java.util.Map, String, String)
static methods.
By default templates are looked up in the handlebars
directory of the application root with a .hbs
suffix.
So handlebarsTemplate("my/template/path")
maps to handlebars/my/template/path.hbs
in the application root directory.
This can be configured using HandlebarsModule.Config.templatesPath(String)
and HandlebarsModule.Config.templatesSuffix(String)
.
Response content type can be manually specified, i.e. handlebarsTemplate("template", model, "text/html")
or can
be detected based on the template extension. Mapping between file extensions and content types is performed using
MimeTypes
contextual object so content type for handlebarsTemplate("template.html")
would be text/html
by default.
Custom handlebars helpers can be registered by binding instances of NamedHelper
.
import ratpack.guice.Guice;
import ratpack.handlebars.HandlebarsModule;
import ratpack.test.embed.BaseDirBuilder;
import ratpack.test.embed.EmbeddedApp;
import java.nio.file.Path;
import static ratpack.handlebars.Template.handlebarsTemplate;
import static org.junit.Assert.*;
public class Example {
public static void main(String... args) throws Exception {
Path baseDir = BaseDirBuilder.tmpDir().build(builder ->
builder.file("handlebars/myTemplate.html.hbs", "Hello {{name}}!")
);
EmbeddedApp.of(baseDir, s -> s
.registry(Guice.registry(b -> b.add(HandlebarsModule.class)))
.handlers(chain -> chain
.get(ctx -> ctx.render(handlebarsTemplate("myTemplate.html", m -> m.put("name", "Ratpack"))))
)
).test(httpClient -> {
assertEquals("Hello Ratpack!", httpClient.getText());
});
}
}
Modifier and Type | Class and Description |
---|---|
static class |
HandlebarsModule.Config |
Constructor and Description |
---|
HandlebarsModule() |
Modifier and Type | Method and Description |
---|---|
protected void |
configure() |
configure, createConfig, defaultConfig, setConfig
addError, addError, addError, bind, bind, bind, bindConstant, binder, bindInterceptor, bindListener, bindListener, bindScope, configure, convertToTypes, currentStage, getMembersInjector, getMembersInjector, getProvider, getProvider, install, requestInjection, requestStaticInjection, requireBinding, requireBinding
protected void configure()
configure
in class AbstractModule