From d1357f3484498f0dc3e883896b29b880c284a0a9 Mon Sep 17 00:00:00 2001 From: Sahaja Lal Date: Mon, 11 Jun 2018 10:59:24 -0600 Subject: [PATCH] Implement config option to transform values used in #set --- src/compile/index.js | 18 +++++++++++------- src/compile/set.js | 14 ++++++-------- tests/compile.js | 13 +++++++++++++ 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/compile/index.js b/src/compile/index.js index dfb5b12..9744a03 100644 --- a/src/compile/index.js +++ b/src/compile/index.js @@ -2,13 +2,17 @@ var utils = require('../utils'); var Helper = require('../helper/index'); function Velocity(asts, config) { this.asts = asts; - this.config = { - // 自动输出为经过html encode输出 - escape: true, - // 不需要转义的白名单 - unescape: {} - }; - utils.mixin(this.config, config); + this.config = Object.assign( + {}, + { + // 自动输出为经过html encode输出 + escape: true, + // 不需要转义的白名单 + unescape: {}, + valueMapper: value => value + }, + config + ); this._state = { stop: false, break: false }; this.init(); } diff --git a/src/compile/set.js b/src/compile/set.js index 8805d7b..5b24709 100644 --- a/src/compile/set.js +++ b/src/compile/set.js @@ -1,4 +1,4 @@ -module.exports = function(Velocity, utils){ +module.exports = function(Velocity, utils) { /** * 变量设置 */ @@ -6,7 +6,7 @@ module.exports = function(Velocity, utils){ /** * 获取执行环境,对于macro中定义的变量,为局部变量,不贮存在全局中,执行后销毁 */ - getContext: function(){ + getContext: function() { var condition = this.condition; var local = this.local; if (condition) { @@ -18,9 +18,9 @@ module.exports = function(Velocity, utils){ /** * parse #set */ - setValue: function(ast){ + setValue: function(ast) { var ref = ast.equal[0]; - var context = this.getContext(); + var context = this.getContext(); // @see #25 if (this.condition && this.condition.indexOf('macro:') === 0) { @@ -36,7 +36,7 @@ module.exports = function(Velocity, utils){ if (valAst.type === 'math') { val = this.getExpression(valAst); } else { - val = this.getLiteral(ast.equal[1]); + val = this.config.valueMapper(this.getLiteral(ast.equal[1])); } if (!ref.path) { @@ -54,9 +54,7 @@ module.exports = function(Velocity, utils){ var len = ref.path ? ref.path.length: 0; const self = this; - //console.log(val); - utils.some(ref.path, function(exp, i){ - + utils.some(ref.path, function(exp, i) { var isEnd = len === i + 1; var key = exp.id; if (exp.type === 'index') { diff --git a/tests/compile.js b/tests/compile.js index 61ebecb..6c19d50 100644 --- a/tests/compile.js +++ b/tests/compile.js @@ -187,6 +187,19 @@ describe('Compile', function() { assert.equal('<i>', ret) }) + it ('valueMapper support', () => { + const values = []; + const vm = '#set($foo = "bar")\n$foo' + const ret = render(vm, {}, {}, { + valueMapper: (value) => { + values.push(value); + return 'foo'; + }, + }); + assert.deepEqual(values, ['bar']); + assert.equal(ret.trim(), 'foo'); + }); + describe('env', function() { it('should throw on property when parent is null', function() { var vm = '$foo.bar';