all files / liquidjs/tags/ if.js

100% Statements 20/20
100% Branches 2/2
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 36 37 38 39 40 41 42 43 44   111×     25× 25×   25× 25× 25×                 14× 23× 42×       25×       24× 25× 25× 25× 10×     14×        
const Liquid = require('..')
 
module.exports = function (liquid) {
  liquid.registerTag('if', {
 
    parse: function (tagToken, remainTokens) {
      this.branches = []
      this.elseTemplates = []
 
      var p
      var stream = liquid.parser.parseStream(remainTokens)
        .on('start', () => this.branches.push({
          cond: tagToken.args,
          templates: (p = [])
        }))
        .on('tag:elsif', token => {
          this.branches.push({
            cond: token.args,
            templates: p = []
          })
        })
        .on('tag:else', () => (p = this.elseTemplates))
        .on('tag:endif', token => stream.stop())
        .on('template', tpl => p.push(tpl))
        .on('end', x => {
          throw new Error(`tag ${tagToken.raw} not closed`)
        })
 
      stream.start()
    },
 
    render: function (scope, hash) {
      for (var i = 0; i < this.branches.length; i++) {
        var branch = this.branches[i]
        var cond = Liquid.evalExp(branch.cond, scope)
        if (Liquid.isTruthy(cond)) {
          return liquid.renderer.renderTemplates(branch.templates, scope)
        }
      }
      return liquid.renderer.renderTemplates(this.elseTemplates, scope)
    }
  })
}