From 7ab0e96419a897378a24c89761d6c978021bcedf Mon Sep 17 00:00:00 2001 From: harttle Date: Tue, 24 Jul 2018 14:49:23 +0800 Subject: [PATCH] feature: template string for {%include%} argument, #72 --- tags/include.js | 42 +++++++++++++++++++++++++++--------------- test/tags/include.js | 8 ++++++++ 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/tags/include.js b/tags/include.js index 3315535f7..d765abe66 100644 --- a/tags/include.js +++ b/tags/include.js @@ -1,3 +1,4 @@ +'use strict' const Liquid = require('..') const lexical = Liquid.lexical const withRE = new RegExp(`with\\s+(${lexical.value.source})`) @@ -7,7 +8,7 @@ const assert = require('../src/util/assert.js') module.exports = function (liquid) { liquid.registerTag('include', { parse: function (token) { - var match = staticFileRE.exec(token.args) + let match = staticFileRE.exec(token.args) if (match) { this.staticValue = match[0] } @@ -23,21 +24,32 @@ module.exports = function (liquid) { } }, render: function (scope, hash) { - var filepath = scope.opts.dynamicPartials - ? Liquid.evalValue(this.value, scope) - : this.staticValue - assert(filepath, `cannot include with empty filename`) - - var originBlocks = scope.opts.blocks - var originBlockMode = scope.opts.blockMode - scope.opts.blocks = {} - scope.opts.blockMode = 'output' - - if (this.with) { - hash[filepath] = Liquid.evalValue(this.with, scope) + 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) } - return liquid.getTemplate(filepath, scope.opts.root) - .then((templates) => { + + 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) }) diff --git a/test/tags/include.js b/test/tags/include.js index fea6334e9..af52a046c 100644 --- a/test/tags/include.js +++ b/test/tags/include.js @@ -23,6 +23,14 @@ describe('tags/include', function () { return expect(liquid.renderFile('/current.html')).to .eventually.equal('barfoobar') }) + it('should support template string', function () { + mock({ + '/current.html': 'bar{% include "bar/{{name}}" %}bar', + '/bar/foo.html': 'foo' + }) + return expect(liquid.renderFile('/current.html', {name: 'foo.html'})).to + .eventually.equal('barfoobar') + }) it('should throw when not specified', function () { mock({