Skip to content

Latest commit

 

History

History
1032 lines (778 loc) · 29.6 KB

README.md

File metadata and controls

1032 lines (778 loc) · 29.6 KB

Become a Patreon Maven Central javadoc

Handlebars.java

Logic-less and semantic Mustache templates with Java

Handlebars handlebars = new Handlebars();

Template template = handlebars.compileInline("Hello {{this}}!");

System.out.println(template.apply("Handlebars.java"));

Output:

Hello Handlebars.java!

Handlebars.java is a Java port of handlebars.

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.

Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.

Requirements

  • Handlebars 4.4+ requires Java 17 or higher.
  • Handlebars 4.3+ requires Java 8 or higher (NOT MAINTAINED).

Getting Started

In general, the syntax of Handlebars templates is a superset of Mustache templates. For basic syntax, check out the Mustache manpage.

The Handlebars.java blog is a good place for getting started too. Javadoc is available at javadoc.io.

Maven

Stable version: Maven Central

  <dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars</artifactId>
    <version>${handlebars-version}</version>
  </dependency>

Loading templates

Templates are loaded using the TemplateLoader class. Handlebars.java provides three implementations of a TemplateLoader:

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

This example loads mytemplate.hbs from the root of the classpath:

mytemplate.hbs:

Hello {{this}}!
var handlebars = new Handlebars();

var template = handlebars.compile("mytemplate");

System.out.println(template.apply("Handlebars.java"));

Output:

Hello Handlebars.java!

You can specify a different TemplateLoader by:

TemplateLoader loader = ...;
Handlebars handlebars = new Handlebars(loader);

Templates prefix and suffix

A TemplateLoader provides two important properties:

  • prefix: useful for setting a default prefix where templates are stored.
  • suffix: useful for setting a default suffix or file extension for your templates. Default is: .hbs

Example:

TemplateLoader loader = new ClassPathTemplateLoader();
loader.setPrefix("/templates");
loader.setSuffix(".html");
Handlebars handlebars = new Handlebars(loader);

Template template = handlebars.compile("mytemplate");

System.out.println(template.apply("Handlebars.java"));

Handlebars.java will resolve mytemplate to /templates/mytemplate.html and load it.

The Handlebars.java Server

The handlebars.java server is small application where you can write Mustache/Handlebars template and merge them with data.

It is a useful tool for Web Designers.

Download from Maven Central:

  1. Go here
  2. Under the Download section click on jar

Maven:

<dependency>
  <groupId>com.github.jknack</groupId>
  <artifactId>handlebars-proto</artifactId>
  <version>${current-version}</version>
</dependency>

Usage: java -jar handlebars-proto-${current-version}.jar -dir myTemplates

Example:

myTemplates/home.hbs

<ul>
 {{#items}}
 {{name}}
 {{/items}}
</ul>

myTemplates/home.json

{
  "items": [
    {
      "name": "Handlebars.java rocks!"
    }
  ]
}

or if you prefer YAML myTemplates/home.yml:

items:
  - name: Handlebars.java rocks!

Open a browser a type:

http://localhost:6780/home.hbs

enjoy it!

Additional options:

  • -dir: set the template directory
  • -prefix: set the template's prefix, default is /
  • -suffix: set the template's suffix, default is .hbs
  • -context: set the context's path, default is /
  • -port: set port number, default is 6780
  • -content-type: set the content-type header, default is text/html

Multiple data sources per template

Sometimes you need or want to test multiple datasets over a single template, you can do that by setting a data parameter in the request URI.

Example:

http://localhost:6780/home.hbs?data=mytestdata

Please note you don't have to specify the extension file.

Helpers

Built-in helpers:

  • with
  • each
  • if
  • unless
  • log
  • block
  • partial
  • precompile
  • embedded
  • i18n and i18nJs
  • string helpers
  • conditional helpers

with, each, if, unless:

See the built-in helper documentation.

block and partial

Block and partial helpers work together to provide you Template Inheritance.

Usage:

  {{#block "title"}}
    ...
  {{/block}}

context: A string literal which defines the region's name.

Usage:

  {{#partial "title"}}
    ...
  {{/partial}}

context: A string literal which defines the region's name.

precompile

Precompile a Handlebars.java template to JavaScript using handlebars.js

user.hbs

Hello {{this}}!

home.hbs

<script type="text/javascript">
{{precompile "user"}}
</script>

Output:

<script type="text/javascript">
(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['user'] = template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;
  var buffer = "", functionType="function", escapeExpression=this.escapeExpression;


  buffer += "Hi ";
  depth0 = typeof depth0 === functionType ? depth0() : depth0;
  buffer += escapeExpression(depth0) + "!";
  return buffer;});
})();
</script>

You can access the precompiled template with:

var template = Handlebars.templates['user']

By default it uses: /handlebars-v1.3.0.js to compile the template. Since handlebars.java 2.x it is also possible to use handlebars.js 2.x

Handlebars handlebars = new Handlebars();
handlebars.handlebarsJsFile("/handlebars-v2.0.0.js");

For more information have a look at the Precompiling Templates documentation.

Usage:

{{precompile "template" [wrapper="anonymous, amd or none"]}}

context: A template name. Required.

wrapper: One of "anonymous", "amd" or "none". Default is: "anonymous"

There is a maven plugin available too.

embedded

The embedded helper allow you to "embedded" a handlebars template inside a <script> HTML tag:

user.hbs

<tr>
  <td>{{firstName}}</td>
  <td>{{lastName}}</td>
</tr>

home.hbs

<html>
...
{{embedded "user"}}
...
</html>

Output:

<html>
...
<script id="user-hbs" type="text/x-handlebars">
<tr>
  <td>{{firstName}}</td>
  <td>{{lastName}}</td>
</tr>
</script>
...
</html>

Usage:

{{embedded "template"}}

context: A template name. Required.

i18n

A helper built on top of a {@link ResourceBundle}. A {@link ResourceBundle} is the most well known mechanism for internationalization (i18n) in Java.

Usage:

{{i18n "hello"}}

This require a messages.properties in the root of classpath.

Using a locale:

{{i18n "hello" locale="es_AR"}}

This requires a messages_es_AR.properties in the root of classpath.

Using a different bundle:

{{i18n "hello" bundle="myMessages"}}

This requires a myMessages.properties in the root of classpath.

Using a message format:

{{i18n "hello" "Handlebars.java"}}

Where hello is Hola {0}!, results in Hola Handlebars.java!.

i18nJs

Translate a ResourceBundle into JavaScript code. The generated code assumes you have the I18n in your application.

Usage:

{{i18nJs [locale] [bundle=messages]}}

If the locale argument is present it will translate that locale to JavaScript. Otherwise, it will use the default locale.

The generated code looks like this:

<script type="text/javascript">
  I18n.defaultLocale = 'es_AR';
  I18n.locale = 'es_AR';
  I18n.translations = I18n.translations || {};
  // Spanish (Argentina)
  I18n.translations['es_AR'] = {
    "hello": "Hi {{arg0}}!"
  }
</script>

Finally, it converts message patterns like: Hi {0} into Hi {{arg0}}. This make possible for the I18n JS library to interpolate variables.

string helpers

Functions like abbreviate, capitalize, join, dateFormat, yesno, etc., are available from StringHelpers.

NOTE: You need to register string helpers (they are not added by default)

conditional helpers

Functions like eq, neq, lt, gt, and, or, not, etc., are available from ConditionalHelpers.

NOTE: You need to register conditional helpers (they are not added by default)

TypeSafe Templates

TypeSafe templates are created by extending the TypeSafeTemplate interface. For example:

// 1
public static interface UserTemplate extends TypeSafeTemplate<User> {

  // 2
  public UserTemplate setAge(int age);

  public UserTemplate setRole(String role);

}

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

userTmpl.setAge(32);

assertEquals("Edgar is 32 years old!", userTmpl.apply(new User("Edgar")));
  1. You extend the TypeSafeTemplate interface.
  2. You add all the set method you need. The set method can returns void or TypeSafeTemplate object.
  3. You create a new type safe template using the: as() method.

Registering Helpers

There are two ways of registering helpers.

Using the Helper interface

handlebars.registerHelper("blog", new Helper<Blog>() {
  public CharSequence apply(Blog blog, Options options) {
    return options.fn(blog);
  }
});
handlebars.registerHelper("blog-list", new Helper<List<Blog>>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String ret = "<ul>";
    for (Blog blog: list) {
      ret += "<li>" + options.fn(blog) + "</li>";
    }
    return new Handlebars.SafeString(ret + "</ul>");
  }
});

Using a HelperSource

A helper source is any class with public methods returning an instance of a CharSequence.

  public static? CharSequence methodName(context?, parameter*, options?) {
  }

Where:

  • A method can/can't be static
  • The method's name becomes the helper's name
  • Context, parameters and options are all optionals
  • If context and options are present they must be the first and last arguments of the method

All these are valid definitions of helper methods:

public class HelperSource {
  public String blog(Blog blog, Options options) {
    return options.fn(blog);
  }

  public static String now() {
    return new Date().toString();
  }

  public String render(Blog context, String param0, int param1, boolean param2, Options options) {
    return ...
  }
}

...

handlebars.registerHelpers(new HelperSource());

Or, if you prefer static methods only:

handlebars.registerHelpers(HelperSource.class);

With plain JavaScript

That's right since 1.1.0 you can write helpers in JavaScript:

helpers.js:

Handlebars.registerHelper('hello', function (context) {
 return 'Hello ' + context;
})
handlebars.registerHelpers(new File("helpers.js"));

Cool, isn't?

Helper Options

Parameters

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String p0 = options.param(0);
    assertEquals("param0", p0);
    Integer p1 = options.param(1);
    assertEquals(123, p1);
    ...
  }
});

Bean bean = new Bean();
bean.setParam1(123);

Template template = handlebars.compileInline("{{#blog-list blogs \"param0\" param1}}{{/blog-list}}");
template.apply(bean);

Default parameters

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String p0 = options.param(0, "param0");
    assertEquals("param0", p0);
    Integer p1 = options.param(1, 123);
    assertEquals(123, p1);
    ...
  }
});

Template template = handlebars.compileInline("{{#blog-list blogs}}{{/blog-list}}");

Hash

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String class = options.hash("class");
    assertEquals("blog-css", class);
    ...
  }
});

handlebars.compileInline("{{#blog-list blogs class=\"blog-css\"}}{{/blog-list}}");

Default hash

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String class = options.hash("class", "blog-css");
    assertEquals("blog-css", class);
    ...
  }
});

handlebars.compileInline("{{#blog-list blogs}}{{/blog-list}}");

Error reporting

Syntax errors

file:line:column: message
   evidence
   ^
[at file:line:column]

Examples:

template.hbs

{{value
/templates.hbs:1:8: found 'eof', expected: 'id', 'parameter', 'hash' or '}'
    {{value
           ^

If a partial isn't found or if it has errors, a call stack is added:

/deep1.hbs:1:5: The partial '/deep2.hbs' could not be found
    {{> deep2
        ^
at /deep1.hbs:1:10
at /deep.hbs:1:10

Helper/Runtime errors

Helper or runtime errors are similar to syntax errors, except for two things:

  1. The location of the problem may (or may not) be the correct one
  2. The stack-trace isn't available

Examples:

Block helper:

public CharSequence apply(final Object context, final Options options) throws IOException {
  if (context == null) {
    throw new IllegalArgumentException(
        "found 'null', expected 'string'");
  }
  if (!(context instanceof String)) {
    throw new IllegalArgumentException(
        "found '" + context + "', expected 'string'");
  }
  ...
}

base.hbs


{{#block}} {{/block}}

Handlebars.java reports:

/base.hbs:2:4: found 'null', expected 'string'
    {{#block}} ... {{/block}}

In short, from a helper you can throw an Exception and Handlebars.java will add the filename, line, column and the evidence.

Advanced Usage

Extending the context stack

Let's say you need to access to the current logged-in user in every single view/page. You can publish the current logged in user by hooking into the context-stack. See it in action:

 hookContextStack(Object model, Template template) {
   User user = ....;// Get the logged-in user from somewhere
   Map moreData = ...;
   Context context = Context
     .newBuilder(model)
       .combine("user", user)
       .combine(moreData)
       .build();
   template.apply(context);
   context.destroy();
 }

Where is the hookContextStack method? Well, it depends on your application architecture.

Using the ValueResolver

By default, Handlebars.java use the JavaBean methods (i.e. public getXxx and isXxx methods) and Map as value resolvers.

You can choose a different value resolver. This section describe how to do this.

The JavaBeanValueResolver

Resolves values from public methods prefixed with "get/is"

Context context = Context
  .newBuilder(model)
  .resolver(JavaBeanValueResolver.INSTANCE)
  .build();

The FieldValueResolver

Resolves values from no-static fields.

Context context = Context
  .newBuilder(model)
  .resolver(FieldValueResolver.INSTANCE)
  .build();

The MapValueResolver

Resolves values from a java.util.Map objects.

Context context = Context
  .newBuilder(model)
  .resolver(MapValueResolver.INSTANCE)
  .build();

The MethodValueResolver

Resolves values from public methods.

Context context = Context
  .newBuilder(model)
  .resolver(MethodValueResolver.INSTANCE)
  .build();

The JsonNodeValueResolver

Resolves values from JsonNode objects.

Context context = Context
  .newBuilder(model)
  .resolver(JsonNodeValueResolver.INSTANCE)
  .build();

Available in Jackson 1.x and Jackson 2.x modules.

Using multiples value resolvers

Context context = Context
  .newBuilder(model)
  .resolver(
      MapValueResolver.INSTANCE,
      JavaBeanValueResolver.INSTANCE,
      FieldValueResolver.INSTANCE
  ).build();

The Cache System

The cache system is designed to provide scalability and flexibility. Here is a quick view of the TemplateCache system:

 public interface TemplateCache {

  /**
   * Remove all mappings from the cache.
   */
  void clear();

  /**
   * Evict the mapping for this source from this cache if it is present.
   *
   * @param source the source whose mapping is to be removed from the cache
   */
  void evict(TemplateSource source);

  /**
   * Return the value to which this cache maps the specified key.
   *
   * @param source source whose associated template is to be returned.
   * @param parser The Handlebars parser.
   * @return A template.
   * @throws IOException If input can't be parsed.
   */
  Template get(TemplateSource source, Parser parser) throws IOException;
}

As you can see, there isn't a put method. All the hard work is done in the get method, which is basically the core of the cache system.

By default, Handlebars.java uses a null cache implementation (a.k.a. no cache at all) which looks like:

Template get(TemplateSource source, Parser parser) throws IOException {
  return parser.parse(source);
}

In addition to the null cache, Handlebars.java provides three more implementations:

  1. ConcurrentMapTemplateCache: a template cache implementation built on top of a ConcurrentMap that detects changes in files automatically. This implementation works very well in general, but there is a small window where two or more threads can compile the same template. This isn't a huge problem with Handlebars.java because the compiler is very very fast. But if for some reason you don't want this, you can use the HighConcurrencyTemplateCache template cache.

  2. HighConcurrencyTemplateCache: a template cache implementation built on top of ConcurrentMap that detects changes in files automatically. This cache implementation eliminates the window created by ConcurrentMapTemplateCache to zero. It follows the patterns described in Java Concurrency in Practice and ensures that a template will be compiled just once regardless of the number of threads.

  3. GuavaTemplateCache: a template cache implementation built on top of Google Guava. Available in handlebars-guava-cache module

You can configure Handlebars.java to use a cache by:

Handlebars hbs = new Handlebars()
  .with(new MyCache());

Using a MissingValueResolver (@deprecated)

NOTE: MissingValueResolver is available in <= 1.3.0. For > 1.3.0 use Helper Missing.

A MissingValueResolver let you use default values for {{variable}} expressions resolved to null.

  MissingValueResolver missingValueResolver = new MissingValueResolver() {
    public String resolve(Object context, String name) {
      //return a default value or throw an exception
      ...;
    }
  };
  Handlebars handlebars = new Handlebars().with(missingValueResolver);

Helper Missing

By default, Handlebars.java throws an java.lang.IllegalArgumentException() if a helper cannot be resolved. You can override the default behaviour by providing a special helper: helperMissing. Example:

  handlebars.registerHelperMissing(new Helper<Object>() {
    @Override
    public CharSequence apply(final Object context, final Options options) throws IOException {
      return options.fn.text();
    }
  });

String form parameters

You can access a parameter name if you set the: stringParams: true. Example:

{{sayHi this edgar}}
  Handlebars handlebars = new Handlebars()
    .stringParams(true);
  
  handlebars.registerHelper("sayHi", new Helper<Object>() {
    public Object apply(Object context, Options options) {
      return "Hello " + options.param(0) + "!";
    }
  });

results in:

Hello edgar!

How does this work? stringParams: true instructs Handlebars.java to resolve a parameter to it's name if the value isn't present in the context stack.

Allow Infinite loops

By default, Handlebars.java doesn't allow a partial to call itself (directly or indirectly). You can change this by setting the: Handlebars.inifiteLoops(true), but watch out for a StackOverflowError.

Pretty Print

The Mustache Spec has some rules for removing spaces and new lines. This feature is disabled by default. You can turn this on by setting the: Handlebars.prettyPrint(true).

Modules

Jackson 1.x

Maven:

 <dependency>
   <groupId>com.github.jknack</groupId>
   <artifactId>handlebars-json</artifactId>
   <version>${handlebars-version}</version>
 </dependency>

Usage:

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

Alternative:

 handlebars.registerHelper("json", new JacksonHelper().viewAlias("myView",
   foo.MyFullyQualifiedClassName.class);
 {{json context [view="myView"] [escapeHTML=false] [pretty=false]}}

context: An object, may be null.

view: The name of the Jackson View. Optional.

escapeHTML: True, if the JSON content contains HTML chars and you need to escaped them. Default is: false.

pretty: True, if the JSON content must be formatted. Default is: false.

Jackson

Maven:

 <dependency>
   <groupId>com.github.jknack</groupId>
   <artifactId>handlebars-jackson</artifactId>
   <version>${handlebars-version}</version>
 </dependency>

SpringMVC

Maven:

 <dependency>
   <groupId>com.github.jknack</groupId>
   <artifactId>handlebars-springmvc</artifactId>
   <version>${handlebars-version}</version>
 </dependency>

Using value resolvers:

 HandlebarsViewResolver viewResolver = ...;

 viewResolver.setValueResolvers(...);

In addition, the HandlebarsViewResolver add a message helper that uses the Spring MessageSource class:

{{message "code" [arg]* [default="default message"]}}

where:

  • code: the message's code. Required.
  • arg: the message's argument. Optional.
  • default: the default's message. Optional.

Checkout the HandlebarsViewResolver.

Performance

Handlebars.java is a modern and full featured template engine, but also has a very good performance (Hbs):

Template Comparison

Benchmark source code is available at: https://github.com/mbosecke/template-benchmark

Architecture and API Design

  • Handlebars.java follows the JavaScript API with some minors exceptions due to the nature of the Java language.
  • The parser is built on top of [ANTLR v4] (http://www.antlr.org/).
  • Data is provided as primitive types (int, boolean, double, etc.), strings, maps, list or JavaBeans objects.
  • Helpers are type-safe.
  • Handlebars.java is thread-safe.

Differences between Handlebars.java and Handlebars.js

Handlebars.java scope resolution follows the Mustache Spec. For example:

Given:

{
  "value": "parent",
  "child": {
  }
}

and

Hello {{#child}}{{value}}{{/child}}

will be:

Hello parent

Now, the same model and template with Handlebars.js is:

Hello 

That is because Handlebars.js doesn't look in the context stack for missing attributes in the current scope (this is consistent with the Mustache Spec).

Hopefully, you can turn-off the context stack lookup in Handlebars.java by qualifying the attribute with this.:

Hello {{#child}}{{this.value}}{{/child}}

Differences between Handlebars.java and Mustache.js

  • Handlebars.java throws a java.io.FileNotFoundException if a partial cannot be loaded.

Status

Mustache 1.0 Compliant

Handlebars.js Compliant

Dependencies

+- org.slf4j:slf4j-api:jar:1.6.4

FAQ

Want to contribute?

  • Fork the project on Github.
  • Wondering what to work on? See task/bug list and pick up something you would like to work on.
  • Do you want to donate one or more helpers? See handlebars=helpers a repository for community's helpers.
  • Create an issue or fix one from issues list.
  • If you know the answer to a question posted to our mailing list - don't hesitate to write a reply.
  • Share your ideas or ask questions on mailing list - don't hesitate to write a reply - that helps us improve javadocs/FAQ.
  • If you miss a particular feature - browse or ask on the mailing list - don't hesitate to write a reply, show us some sample code and describe the problem.
  • Write a blog post about how you use or extend handlebars.java.
  • Please suggest changes to javadoc/exception messages when you find something unclear.
  • If you have problems with documentation, find it non intuitive or hard to follow - let us know about it, we'll try to make it better according to your suggestions. Any constructive critique is greatly appreciated. Don't forget that this is an open source project developed and documented in spare time.

Help and Support

Help and discussion

Bugs, Issues and Features

Related Projects

Author

Edgar Espina

License

Apache License 2