access scope in liquidjs filter
HTML
<script src="https://cdn.jsdelivr.net/npm/liquidjs/dist/liquid.browser.min.js"></script>
<div id="log"></div>
JavaScript
const { Liquid, Tokenizer, evalToken } = liquidjs
const engine = new Liquid()
engine.registerTag('random', {
parse(tagToken) {
const tokenizer = new Tokenizer(tagToken.args)
this.items = []
while (!tokenizer.end()) {
this.items.push(tokenizer.readValue())
}
},
* render(context, emitter) {
const index = Math.floor(this.items.length * Math.random())
const token = this.items[index]
const value = yield evalToken(token, context)
emitter.write(value)
}
})
const tpl = `{% random "foo" bar obj.coo %}`
const scope = { bar: "bar", obj: { coo: "coo" } }
engine.parseAndRender(tpl, scope).then(html => log(html))
function log(text) {
document.querySelector("#log").innerText += text + '\n';
}