public class HandlebarsModule extends AbstractModule
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 setTemplatesPath(String)
and setTemplatesSuffix(String)
as well as
other.handlebars.templatesPath
and other.handlebars.templatesSuffix
configuration properties.
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;
public class Example {
public static void main(String... args) {
Path baseDir = BaseDirBuilder.tmpDir().build(builder ->
builder.file("handlebars/myTemplate.html.hbs", "Hello {{name}}!")
);
EmbeddedApp.fromHandlerFactory(baseDir, launchConfig ->
Guice.builder(launchConfig)
.bindings(b -> b.add(new HandlebarsModule()))
.build(chain -> chain
.get(ctx -> ctx.render(handlebarsTemplate("myTemplate.html", m -> m.put("name", "Ratpack"))))
)
).test(httpClient -> {
assert httpClient.getText().equals("Hello Ratpack!");
});
}
}
Constructor and Description |
---|
HandlebarsModule() |
Modifier and Type | Method and Description |
---|---|
protected void |
configure() |
int |
getCacheSize() |
String |
getTemplatesPath() |
String |
getTemplatesSuffix() |
boolean |
isReloadable() |
void |
setCacheSize(int cacheSize) |
void |
setReloadable(boolean reloadable) |
void |
setTemplatesPath(String templatesPath) |
void |
setTemplatesSuffix(String templatesSuffix) |
addError, addError, addError, bind, bind, bind, bindConstant, binder, bindInterceptor, bindListener, bindListener, bindScope, configure, convertToTypes, currentStage, getMembersInjector, getMembersInjector, getProvider, getProvider, install, requestInjection, requestStaticInjection, requireBinding, requireBinding
public String getTemplatesPath()
public void setTemplatesPath(String templatesPath)
public String getTemplatesSuffix()
public void setTemplatesSuffix(String templatesSuffix)
public int getCacheSize()
public void setCacheSize(int cacheSize)
public boolean isReloadable()
public void setReloadable(boolean reloadable)
protected void configure()
configure
in class AbstractModule