freemarker

freemarker

Freemarker templates for Jooby.

exports

dependency

<dependency>
  <groupId>org.jooby</groupId>
  <artifactId>jooby-ftl</artifactId>
  <version>1.6.6</version>
</dependency>

usage

{
  use(new Ftl());

  get("/", req -> Results.html("index").put("model", new MyModel());
}

public/index.html:

${model}

Templates are loaded from root of classpath: / and must end with: .html file extension.

NOTE: since 1.4.0 Freemarker module uses HTMLOutputFormat which prevent HTML XSS injection. See for more details.

request locals

A template engine has access to request locals (a.k.a attributes). Here is an example:

{
  use(new Ftl());

  get("*", req -> {
    req.set("foo", "bar");
  });
}

Then from template:

${foo}

configuration

There are two ways of changing a Freemarker configuration:

  • via .conf file:
freemarker.default_encoding = UTF-8
  • or programmatically:
{
  use(new Ftl().doWith((freemarker, config) -> {
    freemarker.setDefaultEncoding("UTF-8");
  });
}

Keep in mind this is just an example and you don’t need to set the default encoding. Default encoding is set to: application.charset which is UTF-8 by default.

template loader

Templates are loaded from the root of classpath and must end with .html. You can change the default template location and extensions too:

{
  use(new Ftl("/", ".ftl"));
}

cache

Cache is OFF when env=dev (useful for template reloading), otherwise is ON.

Cache is backed by Guava and default cache will expire after 100 entries.

If 100 entries is not enough or you need a more advanced cache setting, just set the freemarker.cache option:

freemarker.cache = "expireAfterWrite=1h"

See CacheBuilderSpec for more detailed expressions.

freemarker.conf

These are the default properties for ftl:

#freemarker defaults 
freemarker.locale = ${application.lang}

freemarker.number_format = ${application.numberFormat}

freemarker.date_format = ${application.dateFormat}

freemarker.time_zone = ${application.tz}

freemarker.object_wrapper = default

freemarker.template_exception_handler = default

freemarker.defaultEncoding = ${application.charset}

# cache for env != dev 
freemarker.cache = "maximumSize=100"