Skip to content

Commit

Permalink
Implement config option to transform values used in #set
Browse files Browse the repository at this point in the history
  • Loading branch information
lightsofapollo committed Jun 11, 2018
1 parent 8733300 commit d1357f3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
18 changes: 11 additions & 7 deletions src/compile/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
14 changes: 6 additions & 8 deletions src/compile/set.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
module.exports = function(Velocity, utils){
module.exports = function(Velocity, utils) {
/**
* 变量设置
*/
utils.mixin(Velocity.prototype, {
/**
* 获取执行环境,对于macro中定义的变量,为局部变量,不贮存在全局中,执行后销毁
*/
getContext: function(){
getContext: function() {
var condition = this.condition;
var local = this.local;
if (condition) {
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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') {
Expand Down
13 changes: 13 additions & 0 deletions tests/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down

0 comments on commit d1357f3

Please # to comment.