As covered in Register Filters/Tags, we can access filter arguments directly in filter function like:
// Usage: {{ 1 | add: 2, 3 }}
// Output: 6
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)
When it comes to stateful filters, for example transform a URL path to full URL, we’ll need to access a origin
in current scope:
// Usage: {{ '/index.html' | fullURL }}
// Scope: { origin: "https://liquidjs.com" }
// Output: https://liquidjs.com/index.html
engine.registerFilter('fullURL', function (path) {
const origin = this.context.get(['origin'])
return new URL(path, origin).toString()
})
See this JSFiddle: https://jsfiddle.net/ctj364up/1/
Arrow Functions
this
in arrow functions is bound to current JavaScript context, you’ll need to usefunction(){}
instead of()=>{}
syntax to accessthis.context
correctly.