all files / liquidjs/tags/ include.js

100% Statements 38/38
100% Branches 12/12
100% Functions 3/3
100% Lines 38/38
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65    132×   21× 21× 20×     21× 21× 20×     21× 21×       21× 21× 17× 11× 11×           21× 21×   21×   21× 19× 19× 19×   19×     19× 19×     18× 18× 18× 18×          
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
const staticFileRE = /[^\s,]+/
const assert = require('../src/util/assert.js')
 
module.exports = function (liquid) {
  liquid.registerTag('include', {
    parse: function (token) {
      let match = staticFileRE.exec(token.args)
      if (match) {
        this.staticValue = match[0]
      }
 
      match = lexical.value.exec(token.args)
      if (match) {
        this.value = match[0]
      }
 
      match = withRE.exec(token.args)
      if (match) {
        this.with = match[1]
      }
    },
    render: function (scope, hash) {
      let pFilepath
      if (scope.opts.dynamicPartials) {
        if (lexical.quotedLine.exec(this.value)) {
          let template = this.value.slice(1, -1)
          pFilepath = liquid.parseAndRender(template, scope.getAll(), scope.opts)
        } else {
          pFilepath = Promise.resolve(Liquid.evalValue(this.value, scope))
        }
      } else {
        pFilepath = Promise.resolve(this.staticValue)
      }
 
      let originBlocks = scope.opts.blocks
      let originBlockMode = scope.opts.blockMode
 
      return pFilepath
        .then(filepath => {
          assert(filepath, `cannot include with empty filename`)
          scope.opts.blocks = {}
          scope.opts.blockMode = 'output'
          if (this.with) {
            hash[filepath] = Liquid.evalValue(this.with, scope)
          }
          return liquid.getTemplate(filepath, scope.opts.root)
        })
        .then(templates => {
          scope.push(hash)
          return liquid.renderer.renderTemplates(templates, scope)
        })
        .then((html) => {
          scope.pop(hash)
          scope.opts.blocks = originBlocks
          scope.opts.blockMode = originBlockMode
          return html
        })
    }
  })
}