Access Raw Parameters
As covered in Register Filters/Tags, tag parameters is available on tagToken.args as a raw string. For example:
// Usage: {% random foo bar coo %} |
Here’s a JSFiddle version: http://jsfiddle.net/ctj364up/2/
Parse Parameters as Values
Sometimes we need more dynamic tags and want to pass values to the custom tag instead of static strings. Variables in LiquidJS can be literal (string, number, etc.) or a variable from current context scope.
The following modified template also contains 3 values to random from, but they’re values instead of static strings. The first one is string literal, second one is an identifier, third one is a property access sequence containing two identifiers.
{% random "foo" bar obj.coo %} |
It can be tricky to parse all these cases manually, but there’s a Tokenizer class in LiquidJS you can make use of.
const { Liquid, Tokenizer, evalToken } = require('liquidjs') |
Calling this tag in scope { bar: "bar", obj: { coo: "coo" } } yields exactly the same result as the first example. See this JSFiddle: http://jsfiddle.net/ctj364up/3/
Async ans PromisesAsync calls in LiquidJS are implemented by generators directly, for we can call generators in synchronous manner so this tag implementation is also valid for
renderSync(),parseAndRenderSync(),renderFileSync(). If you need to await a promise in tag implementation, simply replaceawait somePromisewithyield somePromiseand keep* render()instead ofasync render()will do the trick. See Sync and Async for more details.
Parse Key-Value Pairs as Named Parameters
Named parameters become very handy when there’re optional parameters or lots of parameters, in which case the order of parameters is not important. This is exactly what Hash class is invented for.
{% random from:2, to:max %} |
In the above example, we’re trying to generate a random number in the range [2, max]. We’ll use Hash to parse from and to parameters.
const { Liquid, Hash } = require('liquidjs') |
Rendering {% random from:2, to:max %} in scope { max: 10 } will generate a random number in the range [2, 10]. See this JSFiddle: http://jsfiddle.net/ctj364up/4/