{"id":28112545,"url":"https://github.com/bkiers/Liqp","last_synced_at":"2025-05-14T05:04:19.362Z","repository":{"id":2583551,"uuid":"3564692","full_name":"bkiers/Liqp","owner":"bkiers","description":"An ANTLR based 'Liquid Template' parser and rendering engine.","archived":false,"fork":false,"pushed_at":"2025-04-03T10:53:37.000Z","size":10666,"stargazers_count":169,"open_issues_count":12,"forks_count":97,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-14T01:49:20.532Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bkiers.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2012-02-27T20:57:32.000Z","updated_at":"2025-04-03T10:53:41.000Z","dependencies_parsed_at":"2023-10-15T00:48:08.539Z","dependency_job_id":"b3654491-846e-49ec-bbbc-c5ee9ad0372b","html_url":"https://github.com/bkiers/Liqp","commit_stats":{"total_commits":513,"total_committers":26,"mean_commits":19.73076923076923,"dds":0.469785575048733,"last_synced_commit":"3825b99068c2213064e777140aa5a9161f8a8bc5"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkiers%2FLiqp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkiers%2FLiqp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkiers%2FLiqp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkiers%2FLiqp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bkiers","download_url":"https://codeload.github.com/bkiers/Liqp/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254076839,"owners_count":22010611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-05-14T05:01:12.713Z","updated_at":"2025-05-14T05:04:19.356Z","avatar_url":"https://github.com/bkiers.png","language":"Java","funding_links":[],"categories":["模板引擎"],"sub_categories":[],"readme":"\u003e [!IMPORTANT]\n\u003e Starting from 0.9.1.0 the [Jsoup transitive dependency removed](https://github.com/bkiers/Liqp/issues/306)\n\n# Liqp \u0026nbsp; [![Build Status](https://github.com/bkiers/Liqp/actions/workflows/ci.yml/badge.svg)](https://github.com/bkiers/Liqp/actions/workflows/ci.yml) [![Maven Central](https://img.shields.io/maven-central/v/nl.big-o/liqp.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22nl.big-o%22%20AND%20a%3A%22liqp%22) ![Branches](.github/badges/branches.svg?)\n\nA Java implementation of the [Liquid templating engine](https://shopify.github.io/liquid) backed\nup by an ANTLR grammar.\n\n## Installation\n\n### Gradle\n\nAdd the dependency:\n\n```groovy\ndependencies {\n  compile 'nl.big-o:liqp:0.9.1.3'\n}\n```\n\n### Maven\n\nAdd the following dependency:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003enl.big-o\u003c/groupId\u003e\n  \u003cartifactId\u003eliqp\u003c/artifactId\u003e\n  \u003cversion\u003e0.9.1.3\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nOr clone this repository and run: `mvn install` which will create a JAR of Liqp\nin your local Maven repository, as well as in the project's `target/` folder.\n\n# Usage\n\nThis library can be used in two different ways:\n\n1. to construct a parse tree of some Liquid input\n2. to render Liquid input source (either files, or input strings)\n\n## 1. Creating a parse tree\n\nTo create a parse tree from input source, do the following:\n\n```java\nString input =\n        \"\u003cul id=\\\"products\\\"\u003e                                               \\n\" +\n                \"  {% for product in products %}                            \\n\" +\n                \"    \u003cli\u003e                                                   \\n\" +\n                \"      \u003ch2\u003e{{ product.name }}\u003c/h2\u003e                          \\n\" +\n                \"      Only {{ product.price | price }}                     \\n\" +\n                \"                                                           \\n\" +\n                \"      {{ product.description | prettyprint | paragraph }}  \\n\" +\n                \"    \u003c/li\u003e                                                  \\n\" +\n                \"  {% endfor %}                                             \\n\" +\n                \"\u003c/ul\u003e                                                      \\n\";\nTemplate template = TemplateParser.DEFAULT.parse(input);\n\nParseTree root = template.getParseTree();\n```\n\nAs you can see, the `getParseTree()` method returns an instance of a\n[`ParseTree`](http://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/ParseTree.html) denoting the root\nnode of the input source. To see how the parse tree is built, you can use `Template#toStringAST()` to print\nan ASCII representation of the tree.\n\n## 2. Render Liquid\n\nIf you're not familiar with Liquid, have a look at their website: [http://liquidmarkup.org](http://liquidmarkup.org).\n\nIn Ruby, you'd render a template like this:\n\n```ruby\n@template = Liquid::Template.parse(\"hi {{name}}\")  # Parses and compiles the template\n@template.render( 'name' =\u003e 'tobi' )               # Renders the output =\u003e \"hi tobi\"\n```\n\nWith Liqp, the equivalent looks like this:\n\n```java\nTemplateParser parser = new TemplateParser.Builder().build();\nTemplate template = parser.parse(\"hi {{name}}\");\nString rendered = template.render(\"name\", \"tobi\");\nSystem.out.println(rendered);\n/*\n    hi tobi\n*/\n```\nThe template variables provided as parameters to `render(...)` can be:\n\n* a [varargs](http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html) where\n  the 0\u003csup\u003eth\u003c/sup\u003e, 2\u003csup\u003end\u003c/sup\u003e, 4\u003csup\u003eth\u003c/sup\u003e, ... indexes must be `String` literals\n  denoting the keys. The values can be any `Object`.\n* a `Map\u003cString, Object\u003e`\n* a JSON string\n* any POJO that is marked with special marker interface `liqp.parser.Inspectable`. In this case the object is converted to `java.util.Map` using jackson's mapper, and so all recipes for configuring jackson conversation will work here.\n* any object that extend special interface `liqp.parser.LiquidSupport` and it is designed for lazy field values computing. It's method `LiquidSupport#toLiquid()` is called only if/when the object is going to be rendered. Since `LiquidSupport` extends `Inspectable` simply use same variant of the `render(...)` method.\n\nThe following examples are equivalent to the previous Liqp example:\n\n#### Map example\n\n```java\nTemplate template = new TemplateParser.Builder().build().parse(\"hi {{name}}\");\nMap\u003cString, Object\u003e map = new HashMap\u003c\u003e();\nmap.put(\"name\", \"tobi\");\nString rendered = template.render(map);\nSystem.out.println(rendered);\n/*\n    hi tobi\n*/\n```\n\n#### JSON example\n\n```java\nTemplate template = new TemplateParser.Builder().build().parse(\"hi {{name}}\");\nString rendered = template.render(\"{\\\"name\\\" : \\\"tobi\\\"}\");\nSystem.out.println(rendered);\n/*\n    hi tobi\n*/\n```\n\n#### Inspectable example\n\n```java\nclass MyParams implements Inspectable {\n    public String name = \"tobi\";\n};\nTemplate template = TemplateParser.DEFAULT.parse(\"hi {{name}}\");\nString rendered = template.render(new MyParams());\nSystem.out.println(rendered);\n/*\n    hi tobi\n*/\n```\n\n#### LiquidSupport example\n```java\nclass MyLazy implements LiquidSupport {\n    @Override\n    public Map\u003cString, Object\u003e toLiquid() {\n        return Collections.singletonMap(\"name\", \"tobi\");\n    }\n};\nTemplate template = TemplateParser.DEFAULT.parse(\"hi {{name}}\");\nString rendered = template.render(new MyLazy());\nSystem.out.println(rendered);\n/*\n    hi tobi\n*/\n```\n\n#### Controlling library behavior\nThe 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:\n* `withFlavor(Flavor flavor)` - flavor of the liquid language. Flavor is nothing else than a predefined set of other settings. Here are supported flavors:\n  * `Flavor.JEKYLL` - flavor that defines all settings, so it tries to behave like jekyll's templates\n  * `Flavor.LIQUID` - the same for liquid's templates\n  * `Flavor.LIQP` (default) - developer of this library found some default behavior of two flavors above somehow weird in selected cases. So this flavor appears.\n* `withStripSingleLine(boolean stripSingleLine)`- if `true` then all blank lines left by outputless tags are removed. Default is `false`.\n* `withStripSpaceAroundTags(boolean stripSpacesAroundTags)` - if `true` then all whitespaces around tags are removed. Default is `false`.\n* `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();`\n* `withTag(Tag tag)` - register custom tag to be used in templates.\n* `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.\n* `withFilter(Filter filter)` - register custom filter to be used in templates. See below for examples.\n* `withEvaluateInOutputTag(boolean evaluateInOutputTag)` - both `Flavor.JEKYLL` and `Flavor.LIQUID` are not allows to evaluate expressions in output tags, simply ignoring the expression and printing out very first token of the expression.  Yes, this: `{{ 97 \u003e 96 }}` will print `97`. This is known [bug/feature](https://github.com/Shopify/liquid/issues/1102) of those templators. If you want to change this behavior and evaluate those expressions, set this flag to `true`. Also, the default flavor `Flavor.LIQP` has this flag set to `true` already. Note: default error mode for `Flavor.LIQUID` is `ERROR` and since `{{ 97 \u003e 96 }}` is invald syntax it will throw error unless less restricted error mode set via `withErrorMode` instruction.\n* `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` -\u003e `null`; `boolean` -\u003e `boolean`; `string` -\u003e `java.lang.String`; any numbers -\u003e `java.math.BigDecimal`, any datetime -\u003e `java.time.ZonedDateTime`. If you want to change this behavior, and allow comparing in expressions in a less restricted way, set this flag to `true`, then the lax (javascript-like) approach for comparing in expressions will be used. Also, the default flavor `Flavor.LIQP` has this flag set to `true` already, others have it `false` by default.\n* `withLiquidStyleInclude(boolean liquidStyleInclude)` - if `true` then include tag will use [syntax from liquid](https://shopify.dev/docs/api/liquid/tags/include), otherwice [jekyll syntax](https://jekyllrb.com/docs/includes/) will be used. Default depends on flavor. `Flavor.LIQUID` and `Flavor.LIQP` has this flag set to `true` already. `Flavor.JEKYLL` has it `false`.\n* `withStrictVariables(boolean strictVariables)` - if set to `true` then all variables must be defined before usage, if some variable is not defined, the exception will be thrown. If `false` then all undefined variables will be treated as `null`. Default is `false`.\n* `withShowExceptionsFromInclude(boolean showExceptionsFromInclude)` - if set to `true` then all exceptions from included templates will be thrown. If `false` then all exceptions from included templates will be ignored. Default is `true`.\n* `withEvaluateMode(TemplateParser.EvaluateMode evaluateMode)` - there exists two rendering modes: `TemplateParser.EvaluateMode.LAZY` and `TemplateParser.EvaluateMode.EAGER`. By default, the `lazy` one is used. This should do the work in most cases. \n  * In `lazy` mode 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.\n  * In `eager` the entire parameter object is converted into plain data tree structure made **only** from maps and lists, so tags/filters do know how to work with these kinds of objects. Special case - temporal objects, they are consumed as is.\n* `withRenderTransformer(RenderTransformer renderTransformer)` - even if most of elements (filters/tags/blocks) returns its results most cases as `String`, the task of combining all those strings into a final result is a task of `liqp.RenderTransformer` implementation. The default `liqp.RenderTransformerDefaultImpl` uses `StringBuilder` for that task, so template rendering is fast. Although, you might have special needs or environment to render the results.\n* `withLocale(Locale locale)` - locale to be used for rendering. Default is `Locale.ENGLISH`. Used mostly for time rendering.\n* `withDefaultTimeZone(ZoneId defaultTimeZone)` - default time zone to be used for rendering. Default is `ZoneId.systemDefault()`. Used mostly for time rendering.\n* `withEnvironmentMapConfigurator(Consumer\u003cMap\u003cString, Object\u003e\u003e configurator)` - if provided then this configurator is called before each template rendering. It can be used to set some global variables for all templates built with given `TemplateParser`. \n* `withSnippetsFolderName(String snippetsFolderName)` - define folder to be used for searching files by `include` tag. Defaults depend on flavor: `Flavor.LIQUID` and `Flavor.LIQP` has this set to `snippets`; `Flavor.JEKYLL` uses `_includes`.\n* `withNameResolver(NameResolver nameResolver)` - if provided then this resolver is used for resolving names of included files. If not provided, then default resolver is used. Default resolver is `liqp.antlr.LocalFSNameResolver` that uses `java.nio.file.Path` for resolving names in local file system. That can be changed to any other resolver, for example, to resolve names in classpath or in remote file system or even build templates dynamically by name.\n* `withMaxIterations(int maxIterations)` - maximum number of iterations allowed in a template. Default is `Integer.MAX_VALUE`. Used to prevent infinite loops. Example use: evaluate templates from untrusted sources.\n* `withMaxSizeRenderedString(int maxSizeRenderedString)` - maximum size of rendered string. Default is `Integer.MAX_VALUE`. Used to prevent out of memory errors. Example use: evaluate templates from untrusted sources.\n* `withMaxRenderTimeMillis(long maxRenderTimeMillis)` - maximum time allowed for template rendering. Default is `Long.MAX_VALUE`. Used to prevent never-ending rendering. Example use: evaluate templates from untrusted sources.\n* `withMaxTemplateSizeBytes(long maxTemplateSizeBytes)` - maximum size of template. Default is `Long.MAX_VALUE`. Used to prevent out of memory errors. Example use: evaluate templates from untrusted sources.\n* `withErrorMode(ErrorMode errorMode)` - error mode to be used. Default is `ErrorMode.STRICT`. \n\n\n### 2.1 Custom filters\n\nLet's say you want to create a custom filter, called `b`, that changes a string like\n`*text*` to `\u003cstrong\u003etext\u003c/strong\u003e`.\n\nYou can do that as follows:\n\n```java\n // first create template parser with new filter\nTemplateParser parser = new TemplateParser.Builder().withFilter(new Filter(\"b\") {\n    @Override\n    public Object apply(Object value, TemplateContext context, Object... params) {\n        // create a string from the value\n        String text = super.asString(value, context);\n\n        // replace and return *...* with \u003cstrong\u003e...\u003c/strong\u003e\n        return text.replaceAll(\"\\\\*(\\\\w(.*?\\\\w)?)\\\\*\", \"\u003cstrong\u003e$1\u003c/strong\u003e\");\n    }\n}).build();\n\n// use your filter\nTemplate template = parser.parse(\"{{ wiki | b }}\");\nString rendered = template.render(\"{\\\"wiki\\\" : \\\"Some *bold* text *in here*.\\\"}\");\nSystem.out.println(rendered);\n/*\n    Some \u003cstrong\u003ebold\u003c/strong\u003e text \u003cstrong\u003ein here\u003c/strong\u003e.\n*/\n```\nAnd to use an optional parameter in your filter, do something like this:\n\n```java\n// first create template parser with your filter\nTemplateParser parser = new TemplateParser.Builder().withFilter(new Filter(\"repeat\"){\n    @Override\n    public Object apply(Object value, TemplateContext context, Object... params) {\n        // get the text of the value\n        String text = super.asString(value, context);\n\n        // check if an optional parameter is provided\n        int times = params.length == 0 ? 1 : super.asNumber(params[0]).intValue();\n\n        StringBuilder builder = new StringBuilder();\n\n        while(times-- \u003e 0) {\n            builder.append(text);\n        }\n\n        return builder.toString();\n    }\n}).build();\n\n// use your filter\nTemplate template = parser.parse(\"{{ 'a' | repeat }}\\n{{ 'b' | repeat:5 }}\");\nString rendered = template.render();\nSystem.out.println(rendered);\n/*\na\nbbbbb\n*/\n```\nYou can use an array (or list) as well, and can also return a numerical value:\n\n```java\nTemplateParser parser = new TemplateParser.Builder().withFilter((new Filter(\"sum\"){\n    @Override\n    public Object apply(Object value, TemplateContext context, Object... params) {\n\n        Object[] numbers = super.asArray(value, context);\n\n        double sum = 0;\n\n        for(Object obj : numbers) {\n            sum += super.asNumber(obj).doubleValue();\n        }\n\n        return sum;\n    }\n})).build();\n\nTemplate template = parser.parse(\"{{ numbers | sum }}\");\nString rendered = template.render(\"{\\\"numbers\\\" : [1, 2, 3, 4, 5]}\");\nSystem.out.println(rendered);\n/*\n    15.0\n*/\n```\nIn short, override one of the `apply()` methods of the `Filter` class to create your own custom filter behavior.\n\n\n\n### 2.2 Tags and blocks\nBoth blocks and tags are kinds of insertions. Literally: `Block extends Insertion` and `Tag extends Insertion`. Class `Insertion` used as basic abstraction for parser. \nBelow is defined the difference between tags and blocks. \n\n#### Tags\nTag is a simple insertion in the template that will be processed and the result of it will be replaced in output, if any. Example is `include` tag: \n```liquid\nSee these data: {% include data.liquid %}\n```\nAnother example is `assign` tag: \n```liquid\n{% assign name='Joe' %}\nHello {{name}}!\n```\nIt has no input but still is an insertion.\n\n#### Blocks\nBlock is a kind of insertions that wraps some text and/or other blocks or tags and performs some operations on the given input. Blocks have opening and closing tags. Example of block is `if`:\n```liquid\n{% if user %} Hello {{ user.name }} {% endif %}\"\n```\nwhere `{% if user %}` is opening tag and `{% endif %}` is closing one. The `user` in this sample is just a parameter for given block.\n\n#### Custom Tags and Blocks\nLet's say you would like to create a block that makes it easy to loop for a fixed number of times executing a block of Liquid code.\n\nHere's a way to create, and use, such a custom `loop` block:\n\n```java\nTemplateParser parser = new TemplateParser.Builder().withBlock(new Block(\"loop\"){\n    @Override\n    public Object render(TemplateContext context, LNode... nodes) {\n        int n = super.asNumber(nodes[0].render(context)).intValue();\n        LNode block = nodes[1];\n        StringBuilder builder = new StringBuilder();\n        while(n-- \u003e 0) {\n            builder.append(super.asString(block.render(context), context));\n        }\n        return builder.toString();\n    }\n}).build();\n\nTemplate template = parser.parse(\"{% loop 5 %}looping!\\n{% endloop %}\");\nString rendered = template.render();\nSystem.out.println(rendered);\n/*\n    looping!\n    looping!\n    looping!\n    looping!\n    looping!\n*/\n```\n\nFor registering custom Tags there exists equivalent `Builder.withTag` function.\n\n## Build and Release\n\nUse Maven 3.5.0 and run build with\n\n```\nmvn clean install\n````\n\nRelease process into the [Central Repository](https://oss.sonatype.org/#welcome) is\nperformed with\n\n```\n mvn release:clean release:prepare release:perform -P ossrh-release\n```\nMake sure having in `~/.m2/settings.xml` this config(with your values):\n```xml\n\u003csettings\u003e\n\u003cservers\u003e\n  \u003cserver\u003e\n    \u003cid\u003eossrh\u003c/id\u003e\n    \u003cusername\u003eMY_OSSRH_USERNAME\u003c/username\u003e\n    \u003cpassword\u003eMY_OSSRH_PASSWORD\u003c/password\u003e\n  \u003c/server\u003e\n\u003c/servers\u003e\n  \u003cprofiles\u003e\n    \u003cprofile\u003e\n      \u003cid\u003eossrh-release\u003c/id\u003e\n      \u003cactivation\u003e\n        \u003cactiveByDefault\u003efalse\u003c/activeByDefault\u003e\n      \u003c/activation\u003e\n      \u003cproperties\u003e\n        \u003cgpg.executable\u003egpg2\u003c/gpg.executable\u003e\n        \u003cgpg.passphrase\u003eGPG_PRIVATE_KEY_PASSWORD\u003c/gpg.passphrase\u003e\n      \u003c/properties\u003e\n    \u003c/profile\u003e\n  \u003c/profiles\u003e\n\u003c/settings\u003e\n```\nAfter executing this go to https://oss.sonatype.org/index.html#stagingRepositories, ensure all is OK, after you can \"Close\" the staging for promoting to the realease and after do \"Release\".\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkiers%2FLiqp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbkiers%2FLiqp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkiers%2FLiqp/lists"}