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). Currently used in production to render thousands of websites with hundreds of millions of page views per month on the HubSpot CMS.
Note: Requires Java >= 8. Originally forked from jangod.
<dependency>
<groupId>com.hubspot.jinjava</groupId>
<artifactId>jinjava</artifactId>
<version>{ LATEST_VERSION }</version>
</dependency>where LATEST_VERSION is the latest version from CHANGES.
or if you're stuck on java 7:
<dependency>
<groupId>com.hubspot.jinjava</groupId>
<artifactId>jinjava</artifactId>
<version>2.0.11-java7</version>
</dependency>my-template.html:
<div>Hello, {{ name }}!</div>java code:
Jinjavajinjava = newJinjava();
Map<String, Object> context = Maps.newHashMap();
context.put("name", "Jared");
Stringtemplate = Resources.toString(Resources.getResource("my-template.html"), Charsets.UTF_8);
StringrenderedTemplate = jinjava.render(template, context);result:
<div>Hello, Jared!</div>Voila!
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 only a ClasspathResourceLocator which will allow loading from ANY file in the classpath inclusing class files. If you want to allow Jinjava to load any file from the
file system, you can add a FileResourceLocator. Be aware the security risks of allowing user input to prevent a user
from adding code such as {% include '/etc/password' %}.
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:
JinjavaConfigconfig = JinjavaConfig.builder().build();
Jinjavajinjava = newJinjava(config);
jinjava.setResourceLocator(newMyCustomResourceLocator());To use more than one ResourceLocator, use a CascadingResourceLocator.
JinjavaConfigconfig = JinjavaConfig.builder().build();
Jinjavajinjava = newJinjava(config);
jinjava.setResourceLocator(newMyCustomResourceLocator(), newFileResourceLocator());You can provide custom jinja tags, filters, and static functions to the template engine.
// define a custom tag implementing com.hubspot.jinjava.lib.Tagjinjava.getGlobalContext().registerTag(newMyCustomTag());
// define a custom filter implementing com.hubspot.jinjava.lib.Filterjinjava.getGlobalContext().registerFilter(newMyAwesomeFilter());
// define a custom public static function (this one will bind to myfn:my_func('foo', 42))jinjava.getGlobalContext().registerFunction(newELFunctionDefinition("myfn", "my_func", MyFuncsClass.class, "myFunc", String.class, Integer.class);
// define any number of classes which extend Importablejinjava.getGlobalContext().registerClasses(Class<? extendsImportable>... classes);