Java-based template engine based on django template syntax, adapted to render jinja templates (at least the subset of jinja in use in HubSpot content). Note: Requires Java >= 7. Originally forked from jangod.
<dependency>
<groupId>com.hubspot.jinjava</groupId>
<artifactId>jinjava</artifactId>
<version>1.0.0</version>
</dependency>
my-template.html:
<div>Hello, {{ name }}!</div>
java code:
Jinjava jinjava = new Jinjava();
Map<String, Object> context = Maps.newHashMap();
context.put("name", "Jared");
String template = Resources.toString(Resources.getResource("my-template.html"), Charsets.UTF_8);
String renderedTemplate = jinjava.render(template, context);
result:
<div>Hello, Handsome!</div>
Voila! Hey, wait a minute...
Jinjava needs to know how to interpret template paths, so it can properly handle tags like:
{% extends "foo/bar/base.html" %}
By default, it will load a FileLocator
; you will likely want to provide your own implementation of
ResourceLoader
to hook into your application's template repository, and then tell jinjava about it:
JinjavaConfig config = new JinjavaConfig();
config.setResourceLocator(new MyCustomResourceLocator());
Jinjava jinjava = new Jinjava(config);
You can provide custom jinja tags, filters, and static functions to the template engine.
// define a custom tag implementing com.hubspot.jinjava.lib.Tag
jinjava.getTagLibrary().addTag(new MyCustomTag());
// define a custom filter implementing com.hubspot.jinjava.lib.Filter
jinjava.getFilterLibrary().addFilter(new MyAwesomeFilter());
// define a custom public static function (this one will bind to myfn.my_func('foo', 42))
jinjava.getFunctionLibrary().addFunction(new ELFunctionDefinition("myfn", "my_func",
MyFuncsClass.class, "myFunc", String.class, Integer.class);