Class HandlebarsModule

  • All Implemented Interfaces:
    com.google.inject.Module

    public class HandlebarsModule
    extends ConfigurableModule<HandlebarsModule.Config>
    An extension module that provides support for Handlebars.java templating engine.

    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).

    The default template delimiters are {{ }} but can be configured using HandlebarsModule.Config.delimiters(String, 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.EphemeralBaseDir;
     import ratpack.test.embed.EmbeddedApp;
     import java.nio.file.Path;
    
     import static ratpack.handlebars.Template.handlebarsTemplate;
     import static org.junit.jupiter.api.Assertions.*;
    
     public class Example {
       public static void main(String... args) throws Exception {
         EphemeralBaseDir.tmpDir().use(baseDir -> {
           baseDir.write("handlebars/myTemplate.html.hbs", "Hello {{name}}!");
           EmbeddedApp.of(s -> s
             .serverConfig(c -> c.baseDir(baseDir.getRoot()))
             .registry(Guice.registry(b -> b.module(HandlebarsModule.class)))
             .handlers(chain -> chain
               .get(ctx -> ctx.render(handlebarsTemplate("myTemplate.html", m -> m.put("name", "Ratpack"))))
             )
           ).test(httpClient -> {
             assertEquals("Hello Ratpack!", httpClient.getText());
           });
         });
       }
     }
     
    See Also:
    Handlebars.java
    • Constructor Detail

      • HandlebarsModule

        public HandlebarsModule()
    • Method Detail

      • configure

        protected void configure()
        Overrides:
        configure in class com.google.inject.AbstractModule