Handlebars.java

repository·master·Indexed 23 days ago

https://github.com/jknack/handlebars.java

A Java implementation of the Handlebars and Mustache templating engines for building semantic, logic-less templates. It includes features such as TypeSafe templates, template inheritance via block and partial helpers, and internationalization using Java ResourceBundles. The library provides a Maven plugin for precompiling templates to JavaScript and converting ResourceBundles to JS via i18njs, as well as a standalone server (handlebars-proto) for testing templates with data.

Tokens
5K
Snippets
18
Records
26
Agent score
81%

What's inside handlebars.java

  1. Use block and partial helpers for Template Inheritance

    master

    The block and partial helpers work together to enable Template Inheritance.

    • {{#block "name"}}...{{/block}}: Defines a named region in a template.
    • {{#partial "name"}}...{{/partial}}: Defines a partial that can be used to fill a block region.
    {{#block "title"}}
      ...
    {{/block}}
    
    {{#partial "title"}}
      ...
    {{/partial}}
  2. Use the include helper for Mustache-compatible partials

    master

    The include helper is a port of a Handlebars.js feature. It is primarily used if you need to maintain compatibility with templates written for Handlebars.js that rely on specific partial implementation behaviors.

    Note: In Handlebars.java, all features provided by the include helper are natively supported using standard partials.

  3. Quickstart with Handlebars.java

    master

    Handlebars.java is a Java port of Handlebars/Mustache. You can use compileInline to create a template directly from a string and apply to render it with data.

    Handlebars handlebars = new Handlebars();
    
    Template template = handlebars.compileInline("Hello {{this}}!");
    
    System.out.println(template.apply("Handlebars.java"));
  4. Run the Handlebars.java Server

    master

    The handlebars-proto artifact provides a small standalone server useful for web designers to test Mustache/Handlebars templates with data. You can run it as a JAR file and point it to a directory containing your .hbs templates and corresponding .json or .yml data files.

    To use the server:

    1. Download the handlebars-proto JAR from Maven Central.
    2. Run the JAR using the -dir flag to specify your template directory.
    3. Access templates via a browser at http://localhost:6780/template_name.hbs.

    You can also test multiple datasets for a single template by appending a data parameter to the URI (e.g., ?data=mytestdata).

    java -jar handlebars-proto-${current-version}.jar -dir myTemplates
  5. Install Handlebars.java via Maven

    master

    Add the following dependency to your pom.xml to use Handlebars.java. Ensure you replace ${handlebars-version} with the desired stable version.

    <dependency>
      <groupId>com.github.jknack</groupId>
      <artifactId>handlebars</artifactId>
      <version>${handlebars-version}</version>
    </dependency>
  6. Convert Java Resource Bundles to JavaScript with i18njs

    master

    The i18njs goal converts Java ResourceBundle files into JavaScript files using the i18n.js API. This allows you to use your Java localization bundles directly in client-side JavaScript code.

    You can trigger this during the prepare-package phase or via the command line.

    <plugin>
      <groupId>com.github.jknack</groupId>
      <artifactId>handlebars-maven-plugin</artifactId>
      <version>${handlebars-version}</version>
      <executions>
        <execution>
          <id>i18njs</id>
          <phase>prepare-package</phase>
          <goals>
            <goal>i18njs</goal>
          </goals>
          <configuration>
            <output>${project.build.directory}/${project.build.finalName}/js</output>
            <bundle>messages</bundle>
            <merge>false</merge>
            <amd>false</amd>
            <encoding>UTF-8</encoding>
          </configuration>
        </execution>
      </executions>
    </plugin>

    Or via CLI:

    mvn handlebars:i18njs
  7. Precompile Handlebars/Mustache templates with handlebars-maven-plugin

    master

    Use the precompile goal of the handlebars-maven-plugin to convert Handlebars or Mustache templates into JavaScript files using the handlebars.js runtime. This is useful for client-side rendering where templates need to be pre-processed.

    You can run this via the Maven lifecycle (typically during prepare-package) or manually using the command line.

    <plugin>
      <groupId>com.github.jknack</groupId>
      <artifactId>handlebars-maven-plugin</artifactId>
      <version>${handlebars-version}</version>
      <executions>
        <execution>
          <id>precompile</id>
          <phase>prepare-package</phase>
          <goals>
            <goal>precompile</goal>
          </goals>
          <configuration>
            <output>${project.build.directory}/${project.build.finalName}/js/helpers.js</output>
            <prefix>${basedir}/src/main/webapp</prefix>
            <suffix>.hbs</suffix>
            <handlebarsJsFile>/handlebars-v1.3.0.js</handlebarsJsFile>
            <minimize>false</minimize>
            <runtime></runtime>
            <amd>false</amd>
            <encoding>UTF-8</encoding>
            <templates>
              <template>mytemplateA</template>
              <template>mytemplateB</template>
            </templates>
          </configuration>
        </execution>
      </executions>
    </plugin>

    Or via CLI:

    mvn handlebars:precompile
  8. Use number helpers: isEven, isOdd, and stripes

    master

    The NumberHelper provides common functions for working with numbers in templates:

    • isEven: Checks if a number is even.
    • isOdd: Checks if a number is odd.
    • stripes: Typically used for alternating styles (often used in conjunction with even/odd logic).

    These helpers can return a boolean-like string or a specific CSS class name if a second argument is provided.

    {{isEven number}} // output: even
    
    {{isEven number "row-even"}} // output: row-even
  9. Use the assign helper to create temporary variables

    master

    The assign helper allows you to create auxiliary or temporary variables within a template. This is useful for storing the result of a complex expression or a sub-template to be used later in the same template context.

    Usage pattern: {{#assign "variableName"}} expression {{/assign}}

    {{#assign "benefitsTitle"}} benefits.{{type}}.title {{/assign}}
    <span class="benefit-title"> {{i18n benefitsTitle}} </span>
  10. Configure ValueResolvers for data access

    master

    By default, Handlebars.java uses a combination of JavaBeanValueResolver, MapValueResolver, and MethodValueResolver. You can customize how data is resolved from your context using the Context.Builder.

    Available Resolvers:

    • JavaBeanValueResolver.INSTANCE: Resolves via getXXX or isXXX methods.
    • FieldValueResolver.INSTANCE: Resolves via non-static fields.
    • MapValueResolver.INSTANCE: Resolves from java.util.Map objects.
    • MethodValueResolver.INSTANCE: Resolves via any public methods.
    • JsonNodeValueResolver.INSTANCE: Resolves from Jackson JsonNode objects.

    Usage:

    Context context = Context.newBuilder(model)
      .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE)
      .build();
    Context context = Context.newBuilder(model)
      .resolver(JavaBeanValueResolver.INSTANCE)
      .build();
  11. Use Jackson for JSON serialization in templates

    master

    The handlebars-json module allows you to serialize objects to JSON directly within a template using the json helper.

    Usage: {{json context [view="alias"] [escapeHTML=false] [pretty=false]}}

    Options:

    • context: The object to serialize.
    • view: The name of a Jackson View (optional).
    • escapeHTML: Whether to escape HTML characters (default: false).
    • pretty: Whether to format the JSON (default: false).

    Registration:

    handlebars.registerHelper("json", JacksonHelper.INSTANCE);
    {{json context [view="foo.MyFullyQualifiedClassName"] [escapeHTML=false] [pretty=false]}}
  12. Load templates using TemplateLoader

    master

    Templates are loaded via the TemplateLoader interface. By default, Handlebars uses ClassPathTemplateLoader. Other available implementations include:

    • ClassPathTemplateLoader (default)
    • FileTemplateLoader
    • SpringTemplateLoader (available via the handlebars-springmvc module)

    To use a specific loader, pass it to the Handlebars constructor.

    var handlebars = new Handlebars();
    var template = handlebars.compile("mytemplate");
    
    System.out.println(template.apply("Handlebars.java"));