In this section you will learn how to create and use type safe templates in Handlebars.java.
TypeSafe templates are created by extending theTypeSafeTemplate
interface
public interface TypeSafeTemplate<T> {
void apply(T context, Writer writer) throws IOException;
String apply(T context) throws IOException;
}
TheTypeSafeTemplate
interface give you a generic version of theapply
methods, but this isn't all.
UserTemplate
:
public interface UserTemplate extends TypeSafeTemplate<User> {
public UserTemplate setAge(int age);
public UserTemplate setRole(String role);
}
UserTemplate userTmpl = hbs.compileInline("{{name}} is {{age}} years old!")
.as(UserTemplate.class);
userTmpl.setAge(32);
userTmpl.apply(new User("Edgar"));
Beside we have asetAge
method how can we sure that value has been provided?
One alternative, is to provide aMissingValueResolver
to fail ifage
isn't present.
age
is 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"));
Thank you, for reading the Handlebars.java blog.