Liqp
An ANTLR based 'Liquid Template' parser and rendering engine.
Install / Use
/learn @bkiers/LiqpREADME
[!IMPORTANT] Starting from 0.9.1.0 the Jsoup transitive dependency removed
Liqp

A Java implementation of the Liquid templating engine backed up by an ANTLR grammar.
Installation
Gradle
Add the dependency:
dependencies {
compile 'nl.big-o:liqp:0.9.1.3'
}
Maven
Add the following dependency:
<dependency>
<groupId>nl.big-o</groupId>
<artifactId>liqp</artifactId>
<version>0.9.1.3</version>
</dependency>
Or clone this repository and run: mvn install which will create a JAR of Liqp
in your local Maven repository, as well as in the project's target/ folder.
Usage
This library can be used in two different ways:
- to construct a parse tree of some Liquid input
- to render Liquid input source (either files, or input strings)
1. Creating a parse tree
To create a parse tree from input source, do the following:
String input =
"<ul id=\"products\"> \n" +
" {% for product in products %} \n" +
" <li> \n" +
" <h2>{{ product.name }}</h2> \n" +
" Only {{ product.price | price }} \n" +
" \n" +
" {{ product.description | prettyprint | paragraph }} \n" +
" </li> \n" +
" {% endfor %} \n" +
"</ul> \n";
Template template = TemplateParser.DEFAULT.parse(input);
ParseTree root = template.getParseTree();
As you can see, the getParseTree() method returns an instance of a
ParseTree denoting the root
node of the input source. To see how the parse tree is built, you can use Template#toStringAST() to print
an ASCII representation of the tree.
2. Render Liquid
If you're not familiar with Liquid, have a look at their website: http://liquidmarkup.org.
In Ruby, you'd render a template like this:
@template = Liquid::Template.parse("hi {{name}}") # Parses and compiles the template
@template.render( 'name' => 'tobi' ) # Renders the output => "hi tobi"
With Liqp, the equivalent looks like this:
TemplateParser parser = new TemplateParser.Builder().build();
Template template = parser.parse("hi {{name}}");
String rendered = template.render("name", "tobi");
System.out.println(rendered);
/*
hi tobi
*/
The template variables provided as parameters to render(...) can be:
- a varargs where
the 0<sup>th</sup>, 2<sup>nd</sup>, 4<sup>th</sup>, ... indexes must be
Stringliterals denoting the keys. The values can be anyObject. - a
Map<String, Object> - a JSON string
- any POJO that is marked with special marker interface
liqp.parser.Inspectable. In this case the object is converted tojava.util.Mapusing jackson's mapper, and so all recipes for configuring jackson conversation will work here. - any object that extend special interface
liqp.parser.LiquidSupportand it is designed for lazy field values computing. It's methodLiquidSupport#toLiquid()is called only if/when the object is going to be rendered. SinceLiquidSupportextendsInspectablesimply use same variant of therender(...)method.
The following examples are equivalent to the previous Liqp example:
Map example
Template template = new TemplateParser.Builder().build().parse("hi {{name}}");
Map<String, Object> map = new HashMap<>();
map.put("name", "tobi");
String rendered = template.render(map);
System.out.println(rendered);
/*
hi tobi
*/
JSON example
Template template = new TemplateParser.Builder().build().parse("hi {{name}}");
String rendered = template.render("{\"name\" : \"tobi\"}");
System.out.println(rendered);
/*
hi tobi
*/
Inspectable example
class MyParams implements Inspectable {
public String name = "tobi";
};
Template template = TemplateParser.DEFAULT.parse("hi {{name}}");
String rendered = template.render(new MyParams());
System.out.println(rendered);
/*
hi tobi
*/
LiquidSupport example
class MyLazy implements LiquidSupport {
@Override
public Map<String, Object> toLiquid() {
return Collections.singletonMap("name", "tobi");
}
};
Template template = TemplateParser.DEFAULT.parse("hi {{name}}");
String rendered = template.render(new MyLazy());
System.out.println(rendered);
/*
hi tobi
*/
Controlling library behavior
The library has a set of keys to control the parsing/rendering process. Even if you might think that's too many of them, the defaults will work for you in most cases. All of them are set on TemplateParser.Builder class. Here they are:
withFlavor(Flavor flavor)- flavor of the liquid language. Flavor is nothing else than a predefined set of other settings. Here are supported flavors:Flavor.JEKYLL- flavor that defines all settings, so it tries to behave like jekyll's templatesFlavor.LIQUID- the same for liquid's templatesFlavor.LIQP(default) - developer of this library found some default behavior of two flavors above somehow weird in selected cases. So this flavor appears.
withStripSingleLine(boolean stripSingleLine)- iftruethen all blank lines left by outputless tags are removed. Default isfalse.withStripSpaceAroundTags(boolean stripSpacesAroundTags)- iftruethen all whitespaces around tags are removed. Default isfalse.withObjectMapper(ObjectMapper mapper)- if provided then this mapper is used for converting json strings to objects and internal object conversion. If not provided, then default mapper is used. Default one is good. Also, the default one is always accessible via TemplateContext instance:context.getParser().getMapper();withTag(Tag tag)- register custom tag to be used in templates.withBlock(Block block)- register custom block to be used in templates. The difference between tag and block is that block has open and closing tag and can contain other content like a text, tags and blocks.withFilter(Filter filter)- register custom filter to be used in templates. See below for examples.withEvaluateInOutputTag(boolean evaluateInOutputTag)- bothFlavor.JEKYLLandFlavor.LIQUIDare not allows to evaluate expressions in output tags, simply ignoring the expression and printing out very first token of the expression. Yes, this:{{ 97 > 96 }}will print97. This is known bug/feature of those templators. If you want to change this behavior and evaluate those expressions, set this flag totrue. Also, the default flavorFlavor.LIQPhas this flag set totruealready. Note: default error mode forFlavor.LIQUIDisERRORand since{{ 97 > 96 }}is invald syntax it will throw error unless less restricted error mode set viawithErrorModeinstruction.withStrictTypedExpressions(boolean strictTypedExpressions)- ruby is strong-typed language. So comparing different types is not allowed there. This library tries to mimic ruby's type system in a way so all not explicit types (created or manipulated inside of templates) are converted with this schema:nil->null;boolean->boolean;string->java.lang.String; any numbers ->java.math.BigDecimal, any datetime ->java.time.ZonedDateTime. If you want to change this behavior, and allow comparing in expressions in a less restricted way, set this flag totrue, then the lax (javascript-like) approach for comparing in expressions will be used. Also, the default flavorFlavor.LIQPhas this flag set totruealready, others have itfalseby default.withLiquidStyleInclude(boolean liquidStyleInclude)- iftruethen include tag will use syntax from liquid, otherwice jekyll syntax will be used. Default depends on flavor.Flavor.LIQUIDandFlavor.LIQPhas this flag set totruealready.Flavor.JEKYLLhas itfalse.withStrictVariables(boolean strictVariables)- if set totruethen all variables must be defined before usage, if some variable is not defined, the exception will be thrown. Iffalsethen all undefined variables will be treated asnull. Default isfalse.withShowExceptionsFromInclude(boolean showExceptionsFromInclude)- if set totruethen all exceptions from included templates will be thrown. Iffalsethen all exceptions from included templates will be ignored. Default istrue.withEvaluateMode(TemplateParser.EvaluateMode evaluateMode)- there exists two rendering modes:TemplateParser.EvaluateMode.LAZYandTemplateParser.EvaluateMode.EAGER. By default, thelazyone is used. This should do the work in most cases.- In
lazymode the template parameters are evaluating on demand and specific properties are read from there only if they are needed. Each filter/tag trying to do its work with its own parameter object, that can be literally anything. - In
eagerthe entire parameter object is converted into
- In
