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 } = liquidjs
const engine = new Liquid()
engine.registerTag('repeat', {
parse(tagToken, remainTokens) {
this.tpls = []
this.liquid.parser.parseStream(remainTokens)
.on('template', tpl => this.tpls.push(tpl))
.on('tag:endrepeat', function () { this.stop() })
.on('end', () => { throw new Error(`tag ${tagToken.getText()} not closed`) })
.start()
},
* render(context, emitter) {
const repeat = { i: 1 }
context.push({ repeat })
yield this.liquid.renderer.renderTemplates(this.tpls, context, emitter)
repeat.i++
yield this.liquid.renderer.renderTemplates(this.tpls, context, emitter)
context.pop()
}
})
const tpl = `
{% repeat %}
{{ repeat.i }}. {{ "hello world" | capitalize}}
{% endrepeat %}`
const html = engine.parseAndRenderSync(tpl)
log.innerText = html