Handlebars.java

Logic-less and semantic templates with Java


by Edgar Espina Theme by mattgraham

TypeSafe templates in Handlebars.java

In this section you will learn how to create and use type safe templates in Handlebars.java.

TypeSafe templates are created by extending theTypeSafeTemplateinterface

public interface TypeSafeTemplate<T> {

  void apply(T context, Writer writer) throws IOException;

  String apply(T context) throws IOException;
}

TheTypeSafeTemplateinterface give you a generic version of theapplymethods, but this isn't all.

Creating a type safe template

Let's see how to create aUserTemplate:
public interface UserTemplate extends TypeSafeTemplate<User> {

  public UserTemplate setAge(int age);

  public UserTemplate setRole(String role);
}
Instantiating a user template:
UserTemplate userTmpl = hbs.compileInline("{{name}} is {{age}} years old!")
  .as(UserTemplate.class);

userTmpl.setAge(32);

userTmpl.apply(new User("Edgar"));

Checking if a variable is present

Beside we have asetAgemethod how can we sure that value has been provided? One alternative, is to provide aMissingValueResolverto fail ifageisn't present.

Failing ifageis missing:
MissingValueResolver missingValueResolver = new MissingValueResolver() {
    public String resolve(Object context, String name) {
      throw new IllegalStateException("Missing variable: " + name);
    }
  };
Handlebars hbs = new Handlebars().with(missingValueResolver);

UserTemplate userTmpl = hbs.compileInline("{{name}} is {{age}} years old!")
  .as(UserTemplate.class);

userTmpl.setAge(32);

userTmpl.apply(new User("Edgar"));

Want to contribute?

Thank you, for reading the Handlebars.java blog.