all files / liquidjs/tags/ capture.js

100% Statements 21/21
100% Branches 0/0
100% Functions 3/3
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35    132×   10× 10×                        
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const re = new RegExp(`(${lexical.identifier.source})`)
const assert = require('../src/util/assert.js')
const types = require('../src/scope.js').types
 
module.exports = function (liquid) {
  liquid.registerTag('capture', {
    parse: function (tagToken, remainTokens) {
      var match = tagToken.args.match(re)
      assert(match, `${tagToken.args} not valid identifier`)
 
      this.variable = match[1]
      this.templates = []
 
      var stream = liquid.parser.parseStream(remainTokens)
      stream.on('tag:endcapture', token => stream.stop())
        .on('template', tpl => this.templates.push(tpl))
        .on('end', x => {
          throw new Error(`tag ${tagToken.raw} not closed`)
        })
      stream.start()
    },
    render: function (scope, hash) {
      return liquid.renderer.renderTemplates(this.templates, scope)
        .then((html) => {
          let ctx = Object.create(types.CaptureScope)
          ctx[this.variable] = html
          scope.push(ctx)
        })
    }
  })
}