Socket
Socket
Sign inDemoInstall

velocityjs

Package Overview
Dependencies
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

velocityjs - npm Package Compare versions

Comparing version 0.5.0-alpha.6 to 0.6.0

.jscsrc

5

History.md

@@ -0,1 +1,6 @@

## [0.6](https://github.com/shepherdwind/velocity.js/milestones/0.6)
- change: remove Velocity.Parser, change to Velocity.parse [#43](https://github.com/shepherdwind/velocity.js/issues/43)
- feat: add custom blocks support [#44](https://github.com/shepherdwind/velocity.js/issues/44)
## 0.4

@@ -2,0 +7,0 @@

2

package.json
{
"name": "velocityjs",
"description": "Velocity Template Language(VTL) for JavaScript",
"version": "0.5.0-alpha.6",
"version": "0.6.0",
"keywords": [

@@ -6,0 +6,0 @@ "velocity template"

@@ -50,7 +50,6 @@ Velocity - Template Engine

//2. 使用Parser和Compile
var Parser = Velocity.Parser;
//2. 使用parse和Compile
var Compile = Velocity.Compile;
var asts = Parser.parse('string of velocity');
var asts = Velocity.parse('string of velocity');
(new Compile(asts)).render(context, macros);

@@ -57,0 +56,0 @@ ```

'use strict';
module.exports = function(Velocity, utils){
module.exports = function(Velocity, utils) {

@@ -42,3 +42,3 @@ /**

*/
setBlockDefine: function(block){
setBlockDefine: function(block) {
var ast = block[0];

@@ -54,3 +54,3 @@ var _block = block.slice(1);

*/
setBlockMacro: function(block){
setBlockMacro: function(block) {
var ast = block[0];

@@ -69,3 +69,3 @@ var _block = block.slice(1);

*/
getMacro: function(ast){
getMacro: function(ast) {
var macro = this.macros[ast.id];

@@ -82,3 +82,3 @@ var ret = '';

utils.forEach(ast.args, function(a){
utils.forEach(ast.args, function(a) {
jsArgs.push(this.getLiteral(a));

@@ -94,8 +94,12 @@ }, this);

jsmacros.context = this.context;
try {
ret = macro.apply(jsmacros, jsArgs);
} catch(e){
getErrorMessage(ast, e, jsArgs);
} catch(e) {
var pos = ast.pos;
var text = Velocity.Helper.getRefText(ast);
// throws error tree
var err = '\n at ' + text + ' L/N ' + pos.first_line + ':' + pos.first_column;
e.name = '';
e.message += err;
throw new Error(e);
}

@@ -114,3 +118,3 @@

utils.forEach(args, function(ref, i){
utils.forEach(args, function(ref, i) {
if (_call_args[i]) {

@@ -136,3 +140,3 @@ local[ref.id] = this.getLiteral(_call_args[i]);

*/
eval: function(str, local, contextId){
eval: function(str, local, contextId) {

@@ -150,3 +154,3 @@ if (!local) {

var asts = [];
var Parser = Velocity.Parser;
var parse = Velocity.parse;
contextId = contextId || ('eval:' + utils.guid());

@@ -158,5 +162,5 @@

} else if (Parser) {
} else if (parse) {
asts = Parser.parse(str);
asts = parse(str);

@@ -183,3 +187,3 @@ }

*/
getBlockEach: function(block){
getBlockEach: function(block) {

@@ -204,3 +208,3 @@ var ast = block[0];

utils.forEach(_from, function(val, i){
utils.forEach(_from, function(val, i) {

@@ -241,3 +245,3 @@ if (this.setBreak) return;

utils.some(block, function(ast){
utils.some(block, function(ast) {

@@ -263,30 +267,2 @@ if (ast.condition) {

});
function getErrorMessage(ast, e, args) {
var pos = ast.pos;
var text = Velocity.Helper.getRefText(ast);
// throws error tree
var stacks = e.stack.split('\n');
var msgs = [''];
var spase = stacks[1].replace(/^(\s+)\w[\s\S]+$/, '$1');
var err = spase + 'at ' + text + ' L/N ' + pos.first_line + ':' +
pos.first_column + ', args: '+ args;
stacks.some(function(msg, i) {
if (msg.indexOf('Velocity.utils.mixin.getMacro') > -1) {
return true;
}
if (i && msg.indexOf('getErrorMessage') === -1) {
msgs.push(msg);
}
});
msgs.push(err);
e.message += msgs.join('\n');
e.name = '';
throw new Error(e);
}
};

@@ -1,22 +0,3 @@

'use strict';
module.exports = function(Velocity, utils) {
module.exports = function(Velocity, utils){
function step(arr, i) {
var result = '';
i = i || 0;
if (!arr[i]) {
return Promise.resolve('');
}
return new Promise(function(resolve) {
arr[i]().then(function(ret) {
result += ret;
step(arr, i + 1).then(function(ret) {
result += ret;
resolve(result);
});
});
});
}
/**

@@ -26,3 +7,3 @@ * compile

utils.mixin(Velocity.prototype, {
init: function() {
init: function(){
this.context = {};

@@ -43,3 +24,3 @@ this.macros = {};

*/
render: function(context, macros, silence) {
render: function(context, macros, silence){

@@ -49,15 +30,10 @@ this.silence = !!silence;

this.jsmacros = macros || {};
var t1 = utils.now();
var str = this._render();
var t2 = utils.now();
var cost = t2 - t1;
if (!this.config.isAsync) {
var t1 = utils.now();
var str = this._render();
var t2 = utils.now();
var cost = t2 - t1;
this.cost = cost;
this.cost = cost;
return str;
}
return this.asyncRender(this.asts);
return str;
},

@@ -72,4 +48,5 @@

*/
_render: function(asts, contextId) {
_render: function(asts, contextId){
var str = '';
asts = asts || this.asts;

@@ -79,3 +56,3 @@

if (contextId !== this.condition &&
if (contextId !== this.condition &&
utils.indexOf(contextId, this.conditions) === -1) {

@@ -91,48 +68,33 @@ this.conditions.unshift(contextId);

return utils.map(asts, this.compute, this).join('');
},
utils.forEach(asts, function(ast){
asyncRender: function(asts) {
return step(this.toPromises(asts));
},
switch(ast.type) {
case 'references':
str += this.getReferences(ast, true);
break;
compute: function(ast) {
switch (ast.type) {
case 'references':
return this.getReferences(ast, true);
case 'set':
this.setValue(ast);
break;
case 'set':
this.setValue(ast);
return '';
case 'break':
this.setBreak = true;
break;
case 'break':
this.setBreak = true;
return '';
case 'macro_call':
str += this.getMacro(ast);
break;
case 'macro_call':
return this.getMacro(ast);
case 'comment':
break;
case 'comment':
return '';
default:
str += typeof ast == 'string' ? ast : this.getBlock(ast);
break;
}
}, this);
default:
return typeof ast === 'string' ? ast : this.getBlock(ast);
}
},
toPromises: function(asts) {
var self = this;
return utils.map(asts, function(ast) {
return function() {
var ret = self.compute(ast);
if (typeof ret === 'string') {
return Promise.resolve(ret);
}
// 否则是promise对象
return ret;
};
});
return str;
}
});
};

@@ -1,2 +0,1 @@

'use strict';
var utils = require('../utils');

@@ -10,5 +9,3 @@ var Helper = require('../helper/index');

// 不需要转义的白名单
unescape: {},
// 是否支持异步宏
isAsync: false
unescape: {}
};

@@ -15,0 +12,0 @@ utils.mixin(this.config, config);

@@ -1,2 +0,3 @@

module.exports = function(Velocity, utils){
'use strict';
module.exports = function(Velocity, utils) {
/**

@@ -13,3 +14,3 @@ * literal解释模块

*/
getLiteral: function(literal){
getLiteral: function(literal) {

@@ -19,19 +20,19 @@ var type = literal.type;

if (type == 'string') {
if (type === 'string') {
ret = this.getString(literal);
} else if (type == 'integer') {
} else if (type === 'integer') {
ret = parseInt(literal.value, 10);
} else if (type == 'decimal') {
} else if (type === 'decimal') {
ret = parseFloat(literal.value, 10);
} else if (type == 'array') {
} else if (type === 'array') {
ret = this.getArray(literal);
} else if(type == 'map') {
} else if (type === 'map') {

@@ -41,6 +42,6 @@ ret = {};

utils.forEach(map, function(exp, key){
utils.forEach(map, function(exp, key) {
ret[key] = this.getLiteral(exp);
}, this);
} else if(type == 'bool') {
} else if (type === 'bool') {

@@ -67,7 +68,8 @@ if (literal.value === "null") {

*/
getString: function(literal){
getString: function(literal) {
var val = literal.value;
var ret = val;
if (literal.isEval && (val.indexOf('#') !== -1 || val.indexOf("$") !== -1)) {
if (literal.isEval && (val.indexOf('#') !== -1 ||
val.indexOf("$") !== -1)) {
ret = this.evalStr(val);

@@ -85,3 +87,3 @@ }

*/
getArray: function(literal){
getArray: function(literal) {

@@ -117,3 +119,3 @@ var ret = [];

} else {
utils.forEach(literal.value, function(exp){
utils.forEach(literal.value, function(exp) {
ret.push(this.getLiteral(exp));

@@ -129,4 +131,4 @@ }, this);

*/
evalStr: function(str){
var asts = Velocity.Parser.parse(str);
evalStr: function(str) {
var asts = Velocity.parse(str);
return this._render(asts);

@@ -133,0 +135,0 @@ }

@@ -1,6 +0,6 @@

module.exports = function(Velocity, utils){
module.exports = function(Velocity, utils) {
'use strict';
function getSize(obj){
function getSize(obj) {

@@ -19,3 +19,3 @@ if (utils.isArray(obj)) {

*/
function convert(str){
function convert(str) {

@@ -28,12 +28,12 @@ if (typeof str !== 'string') return str;

for(i = 0 ; i < str.length ; i++) {
for (i = 0 ; i < str.length ; i++) {
c = str.charAt(i);
if((' ' <= c && c <= '~') || (c == '\r') || (c == '\n')) {
if(c == '&') {
if ((' ' <= c && c <= '~') || (c === '\r') || (c === '\n')) {
if (c === '&') {
cstr = "&amp;"
escape = true
} else if(c == '<') {
} else if (c === '<') {
cstr = "&lt;"
escape = true
} else if(c == '>') {
} else if (c === '>') {
cstr = "&gt;"

@@ -52,14 +52,38 @@ escape = true

return escape ? result : str
}
function getter(base, property) {
// get(1)
if (typeof property === 'number') {
return base[property];
}
var letter = property.charCodeAt(0);
var isUpper = letter < 91;
var ret = base[property];
if (ret !== undefined) {
return ret;
}
if (isUpper) {
// Address => address
property = String.fromCharCode(letter).toLowerCase() + property.slice(1);
}
if (!isUpper) {
// address => Address
property = String.fromCharCode(letter).toUpperCase() + property.slice(1);
}
return base[property];
}
utils.mixin(Velocity.prototype, {
//增加某些函数,不需要执行html转义
addIgnoreEscpape: function(key){
// 增加某些函数,不需要执行html转义
addIgnoreEscpape: function(key) {
if (!utils.isArray(key)) key = [key]
utils.forEach(key, function(key){
utils.forEach(key, function(key) {
this.config.unescape[key] = true

@@ -108,5 +132,5 @@ }, this)

utils.some(ast.path, function(property){
utils.some(ast.path, function(property) {
//第三个参数,返回后面的参数ast
// 第三个参数,返回后面的参数ast
ret = this.getAttributes(property, ret, ast);

@@ -118,3 +142,3 @@

if (isVal && ret === undefined) {
ret = isSilent? '' : Velocity.Helper.getRefText(ast);
ret = isSilent ? '' : Velocity.Helper.getRefText(ast);
}

@@ -130,3 +154,3 @@

*/
getLocal: function(ast){
getLocal: function(ast) {

@@ -137,3 +161,3 @@ var id = ast.id;

var isLocaled = utils.some(this.conditions, function(contextId){
var isLocaled = utils.some(this.conditions, function(contextId) {
var _local = local[contextId];

@@ -160,3 +184,3 @@ if (id in _local) {

*/
getAttributes: function(property, baseRef, ast){
getAttributes: function(property, baseRef, ast) {
/**

@@ -168,3 +192,3 @@ * type对应着velocity.yy中的attribute,三种类型: method, index, property

var id = property.id;
if (type === 'method'){
if (type === 'method') {
ret = this.getPropMethod(property, baseRef, ast);

@@ -183,8 +207,8 @@ } else if (type === 'property') {

*/
getPropIndex: function(property, baseRef){
getPropIndex: function(property, baseRef) {
var ast = property.id;
var key;
if (ast.type === 'references'){
if (ast.type === 'references') {
key = this.getReferences(ast);
} else if(ast.type === 'integer'){
} else if (ast.type === 'integer') {
key = ast.value;

@@ -201,17 +225,15 @@ } else {

*/
getPropMethod: function(property, baseRef, ast){
getPropMethod: function(property, baseRef, ast) {
var id = property.id;
var ret = '';
var _id = id.slice(3);
var id = property.id;
var ret = '';
// getter 处理
if (id.indexOf('get') === 0 && !(id in baseRef)) {
if (_id) {
ret = baseRef[_id];
if (id.length === 3) {
// get('address')
ret = getter(baseRef, this.getLiteral(property.args[0]));
} else {
//map 对应的get方法
_id = this.getLiteral(property.args[0]);
ret = baseRef[_id];
// getAddress()
ret = getter(baseRef, id.slice(3));
}

@@ -224,5 +246,5 @@

baseRef[_id] = this.getLiteral(property.args[0]);
baseRef[id.slice(3)] = this.getLiteral(property.args[0]);
// $page.setName(123)
baseRef.toString = function() { return ''; };
baseRef.toString = function() { return ''; };
return baseRef;

@@ -232,6 +254,3 @@

_id = id.slice(2);
ret = baseRef[_id];
return ret;
return getter(baseRef, id.slice(2));
} else if (id === 'keySet') {

@@ -244,3 +263,3 @@

ret = [];
utils.forEach(baseRef, function(value, key){
utils.forEach(baseRef, function(value, key) {
ret.push({key: key, value: value});

@@ -260,3 +279,3 @@ });

utils.forEach(property.args, function(exp){
utils.forEach(property.args, function(exp) {
args.push(this.getLiteral(exp));

@@ -275,6 +294,7 @@ }, this);

ret = ret.apply(baseRef, args);
} catch(e) {
} catch (e) {
var pos = ast.pos;
var text = Velocity.Helper.getRefText(ast);
var err = ' on ' + text + ' at L/N ' + pos.first_line + ':' + pos.first_column;
var err = ' on ' + text + ' at L/N ' +
pos.first_line + ':' + pos.first_column;
e.name = '';

@@ -281,0 +301,0 @@ e.message += err;

"use strict";
var utils = {};
['forEach', 'some', 'every', 'filter', 'map'].forEach(function(fnName){
utils[fnName] = function(arr, fn, context){
if (!arr || typeof arr == 'string') return arr;
['forEach', 'some', 'every', 'filter', 'map'].forEach(function(fnName) {
utils[fnName] = function(arr, fn, context) {
if (!arr || typeof arr === 'string') return arr;
context = context || this;
if (arr[fnName]){
if (arr[fnName]) {
return arr[fnName](fn, context);
} else {
var keys = Object.keys(arr);
return keys[fnName](function(key){
return keys[fnName](function(key) {
return fn.call(context, arr[key], key, arr);

@@ -20,9 +20,8 @@ }, context);

var number = 0;
utils.guid = function(){
utils.guid = function() {
return number++;
};
utils.mixin = function (to, from){
utils.forEach(from, function(val, key){
var toString = {}.toString.call(val);
utils.mixin = function(to, from) {
utils.forEach(from, function(val, key) {
if (utils.isArray(val) || utils.isObject(val)) {

@@ -37,11 +36,11 @@ to[key] = utils.mixin(val, to[key] || {});

utils.isArray = function(obj){
utils.isArray = function(obj) {
return {}.toString.call(obj) === '[object Array]';
};
utils.isObject = function(obj){
utils.isObject = function(obj) {
return {}.toString.call(obj) === '[object Object]';
};
utils.indexOf = function(elem, arr){
utils.indexOf = function(elem, arr) {
if (utils.isArray(arr)) {

@@ -55,48 +54,2 @@ return arr.indexOf(elem);

function makeLevel(block, index){
var blockTypes = {
'if': 1,
'foreach': 1,
'macro': 1,
'noescape': 1,
'define': 1
};
var len = block.length;
index = index || 0;
var ret = [];
var ignore = index - 1;
for (var i = index; i < len; i++) {
if (i <= ignore) continue;
var ast = block[i];
var type = ast.type;
if (!blockTypes[type] && type !== 'end') {
ret.push(ast);
} else if (type === 'end') {
return {arr: ret, step: i};
} else {
var _ret = makeLevel(block, i + 1);
ignore = _ret.step;
_ret.arr.unshift(block[i]);
ret.push(_ret.arr);
}
}
return ret;
}
utils.makeLevel = makeLevel;
module.exports = utils;

@@ -1,37 +0,17 @@

var Parser = require('./parse/');
var utils = require('./utils');
'use strict';
var Compile = require('./compile/');
var Helper = require('./helper/index');
var parse = require('./parse');
Compile.Parser = Parser;
Parser._parse = Parser.parse;
Compile.parse = parse;
Parser.parse = function (str) {
var asts = Parser._parse(str);
/**
* remove all newline after all direction such as `#set, #each`
*/
utils.forEach(asts, function trim(ast, i){
var TRIM_REG = /^[ \t]*\n/;
if (ast.type && ast.type !== 'references') {
var _ast = asts[i + 1];
if (typeof _ast === 'string' && TRIM_REG.test(_ast)) {
asts[i + 1] = _ast.replace(TRIM_REG, '');
}
}
});
return utils.makeLevel(asts);
};
var Velocity = {
Parser : Parser,
Compile : Compile,
parse: parse,
Compile: Compile,
Helper: Helper
};
Velocity.render = function (template, context, macros) {
Velocity.render = function(template, context, macros) {
var asts = Parser.parse(template);
var asts = parse(template);
var compile = new Compile(asts);

@@ -38,0 +18,0 @@ return compile.render(context, macros);

@@ -0,12 +1,13 @@

'use strict';
var Velocity = require('../src/velocity')
var assert = require("assert")
var Parser = Velocity.Parser
var parse = Velocity.parse
var Compile = Velocity.Compile
describe('Compile', function(){
describe('Compile', function() {
var render = Velocity.render;
function getContext(str, context, macros){
var compile = new Compile(Parser.parse(str))
function getContext(str, context, macros) {
var compile = new Compile(parse(str))
compile.render(context, macros)

@@ -16,16 +17,32 @@ return compile.context

describe('References', function(){
describe('References', function() {
it('get/is method', function(){
var vm = '$customer.getAddress()'
var vm1 = '$customer.get("Address") $customer.isAddress()'
it('get/is method', function() {
var vm = '$customer.getAddress() $customer.getaddress()'
var vm1 = '$customer.get("address") $customer.get("Address")'
var vm3 = '$customer.isAddress() $customer.isaddress()'
assert.equal('bar' , render(vm, {customer: {Address: "bar"}}))
assert.equal('bar bar', render(vm1, {customer: {Address: "bar"}}))
assert.equal('bar bar', render(vm3, {customer: {Address: "bar"}}))
assert.equal('bar bar', render(vm, {customer: {address: "bar"}}))
assert.equal('foo bar', render(vm, {
customer: {
address: 'bar',
Address: 'foo'
}
}))
assert.equal('bar bar', render(vm1, {customer: {address: "bar"}}))
assert.equal('foo bar', render(vm1, {
customer: {
Address: 'bar',
address: 'foo'
}
}))
})
it('method with attribute', function(){
it('method with attribute', function() {
var vm = '$foo().bar\n${foo().bar}'
assert.equal('hello\nhello', render(vm, {
foo: function(){
foo: function() {
return { bar: 'hello' }

@@ -36,3 +53,3 @@ }

assert.equal('foo', render('${foo()}', {
foo: function(){
foo: function() {
return 'foo'

@@ -43,3 +60,3 @@ }

it('index notation', function(){
it('index notation', function() {
var vm = '$foo[0] $foo[$i] $foo.get(1)'

@@ -49,8 +66,9 @@ assert.equal('bar haha haha', render(vm, {foo: ["bar", "haha"], i: 1}))

it('set method', function(){
var vm = '$page.setTitle( "My Home Page" ).setname("haha")$page.Title $page.name'
it('set method', function() {
var vm = '$page.setTitle("My Home Page").setname("haha")' +
'$page.Title $page.name'
assert.equal('My Home Page haha', render(vm, {page: {}}))
})
it('size method', function(){
it('size method', function() {
var vm = '$foo.bar.size()'

@@ -65,3 +83,3 @@ assert.equal('2', render(vm, {foo: {bar: [1, 2]}}))

it('quiet reference', function(){
it('quiet reference', function() {
var vm = 'my email is $email'

@@ -73,16 +91,16 @@ var vmquiet = 'my email is $!email'

it('silence all reference', function(){
it('silence all reference', function() {
var vm = 'my email is $email'
var compile = new Compile(Parser.parse(vm))
var compile = new Compile(parse(vm))
assert.equal('my email is ', compile.render(null, null, true))
})
it('this context keep correct, see #16', function(){
it('this context keep correct, see #16', function() {
var data = 'a = $a.get()'
Compile.Parser = Parser
function b(c) {
function B(c) {
this.c = c
}
b.prototype.get = function() {
B.prototype.get = function() {
var t = this.eval(" hello $name", {name: 'hanwen'})

@@ -92,3 +110,3 @@ return this.c + t

assert.equal('a = 1 hello hanwen', render(data, {a: new b(1)}))
assert.equal('a = 1 hello hanwen', render(data, {a: new B(1)}))
})

@@ -109,10 +127,9 @@

it('get variable form text', function(){
it('get variable form text', function() {
var vm = 'hello $user.getName().getFullName("hanwen")'
var data = { '$user.getName().getFullName("hanwen")': 'world' }
assert.equal('hello world', render(vm, data))
})
it('escape default', function(){
it('escape default', function() {
var vm = '$name $name2 $cn $cn1'

@@ -130,7 +147,7 @@ var data = {

it('add custom ignore escape function', function(){
it('add custom ignore escape function', function() {
var vm = '$noIgnore($name), $ignore($name)'
var expected = '&lt;i&gt;, <i>'
var compile = new Compile(Parser.parse(vm))
var compile = new Compile(parse(vm))
compile.addIgnoreEscpape('ignore')

@@ -140,7 +157,7 @@

name: '<i>',
noIgnore: function(name){
noIgnore: function(name) {
return name
},
ignore: function(name){
ignore: function(name) {
return name;

@@ -154,10 +171,10 @@ }

it('config support', function(){
it('config support', function() {
var vm = '$foo($name)'
var expected = '<i>'
var compile = new Compile(Parser.parse(vm), { escape: false })
var compile = new Compile(parse(vm), { escape: false })
var context = {
name: '<i>',
foo: function(name){
foo: function(name) {
return name;

@@ -170,34 +187,15 @@ }

compile = new Compile(Parser.parse(vm), { unescape: { foo: true } })
compile = new Compile(parse(vm), { unescape: { foo: true } })
ret = compile.render(context)
assert.equal(expected, ret)
compile = new Compile(Parser.parse(vm))
compile = new Compile(parse(vm))
ret = compile.render(context)
assert.equal('&lt;i&gt;', ret)
})
it('async render support', function(done) {
var vm = 'abc#parse("hello")11'
var macros = {
parse: function(word) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(word);
}, 30);
});
}
};
var compile = new Compile(Parser.parse(vm), { isAsync: true })
compile.render({}, macros).then(function(ret) {
assert.equal(ret, 'abchello11');
done();
});
})
})
describe('Set && Expression', function(){
describe('Set && Expression', function() {
it('set equal to reference', function(){
it('set equal to reference', function() {
var vm = '#set( $monkey = $bill ) ## variable reference'

@@ -207,3 +205,3 @@ assert.equal("hello", getContext(vm, {bill: 'hello'}).monkey)

it('empty map', function(){
it('empty map', function() {
var vm = '#set($foo = {})'

@@ -213,3 +211,3 @@ assert.deepEqual({}, getContext(vm).foo)

it('#set array', function(){
it('#set array', function() {
var vm = '#set($foo = []) #set($foo[0] = 12)'

@@ -219,10 +217,10 @@ assert.equal(12, getContext(vm).foo[0])

it('set equal to literal', function(){
it('set equal to literal', function() {
var vm = "#set( $monkey.Friend = 'monica' ) ## string literal\n" +
'#set( $monkey.Number = 123 ) ##number literal'
assert.equal("monica", getContext(vm).monkey.Friend)
assert.equal("123" , getContext(vm).monkey.Number)
assert.equal("123", getContext(vm).monkey.Number)
})
it('equal to method/property reference', function(){
it('equal to method/property reference', function() {
var vm = "#set($monkey.Blame = $spindoctor.Leak) ## property \n" +

@@ -232,3 +230,3 @@ '#set( $monkey.Plan = $spindoctor.weave($web) ) ## method'

spindoctor: {
weave: function(name){
weave: function(name) {
return name

@@ -241,8 +239,8 @@ },

assert.equal("hello world" , getContext(vm, obj).monkey.Blame)
assert.equal("name" , getContext(vm, obj).monkey.Plan)
assert.equal("hello world", getContext(vm, obj).monkey.Blame)
assert.equal("name", getContext(vm, obj).monkey.Plan)
})
it('equal to map/list', function(){
it('equal to map/list', function() {
var vms = [

@@ -254,49 +252,49 @@ '#set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList',

var list = ["Not", "my", "fault"]
var map = {"banana" : "good", "roast beef" : "bad"}
assert.deepEqual(list , getContext(vms[0], {my: "my"}).monkey.Say)
assert.deepEqual(map , getContext(vms[1]).monkey.Map)
var map = {banana: "good", 'roast beef': "bad"}
assert.deepEqual(list, getContext(vms[0], {my: "my"}).monkey.Say)
assert.deepEqual(map, getContext(vms[1]).monkey.Map)
})
it('expression simple math', function(){
assert.equal(10 , getContext('#set($foo = 2 * 5)').foo)
assert.equal(2 , getContext('#set($foo = 4 / 2)').foo)
assert.equal(-3 , getContext('#set($foo = 2 - 5)').foo)
assert.equal(1 , getContext('#set($foo = 5 % 2)').foo)
assert.equal(7 , getContext('#set($foo = 7)').foo)
it('expression simple math', function() {
assert.equal(10, getContext('#set($foo = 2 * 5)').foo)
assert.equal(2, getContext('#set($foo = 4 / 2)').foo)
assert.equal(-3, getContext('#set($foo = 2 - 5)').foo)
assert.equal(1, getContext('#set($foo = 5 % 2)').foo)
assert.equal(7, getContext('#set($foo = 7)').foo)
})
it('math with decimal', function(){
assert.equal(10.5 , getContext('#set($foo = 2.1 * 5)').foo)
assert.equal(2.1 , getContext('#set($foo = 4.2 / 2)').foo)
assert.equal(-7.5 , getContext('#set($foo = - 2.5 - 5)').foo)
it('math with decimal', function() {
assert.equal(10.5, getContext('#set($foo = 2.1 * 5)').foo)
assert.equal(2.1, getContext('#set($foo = 4.2 / 2)').foo)
assert.equal(-7.5, getContext('#set($foo = - 2.5 - 5)').foo)
})
it('expression complex math', function(){
assert.equal(20 , getContext('#set($foo = (7 + 3) * (10 - 8))').foo)
assert.equal(-20 , getContext('#set($foo = -(7 + 3) * (10 - 8))').foo)
assert.equal(-1 , getContext('#set($foo = -7 + 3 * (10 - 8))').foo)
it('expression complex math', function() {
assert.equal(20, getContext('#set($foo = (7 + 3) * (10 - 8))').foo)
assert.equal(-20, getContext('#set($foo = -(7 + 3) * (10 - 8))').foo)
assert.equal(-1, getContext('#set($foo = -7 + 3 * (10 - 8))').foo)
})
it('expression compare', function(){
assert.equal(false , getContext('#set($foo = 10 > 11)').foo)
assert.equal(true , getContext('#set($foo = 10 < 11)').foo)
assert.equal(true , getContext('#set($foo = 10 != 11)').foo)
assert.equal(true , getContext('#set($foo = 10 <= 11)').foo)
assert.equal(true , getContext('#set($foo = 11 <= 11)').foo)
assert.equal(false , getContext('#set($foo = 12 <= 11)').foo)
assert.equal(true , getContext('#set($foo = 12 >= 11)').foo)
assert.equal(false , getContext('#set($foo = 10 == 11)').foo)
it('expression compare', function() {
assert.equal(false, getContext('#set($foo = 10 > 11)').foo)
assert.equal(true, getContext('#set($foo = 10 < 11)').foo)
assert.equal(true, getContext('#set($foo = 10 != 11)').foo)
assert.equal(true, getContext('#set($foo = 10 <= 11)').foo)
assert.equal(true, getContext('#set($foo = 11 <= 11)').foo)
assert.equal(false, getContext('#set($foo = 12 <= 11)').foo)
assert.equal(true, getContext('#set($foo = 12 >= 11)').foo)
assert.equal(false, getContext('#set($foo = 10 == 11)').foo)
})
it('expression logic', function(){
assert.equal(false , getContext('#set($foo = 10 == 11 && 3 > 1)').foo)
assert.equal(true , getContext('#set($foo = 10 < 11 && 3 > 1)').foo)
assert.equal(true , getContext('#set($foo = 10 > 11 || 3 > 1)').foo)
assert.equal(true , getContext('#set($foo = !(10 > 11) && 3 > 1)').foo)
assert.equal(false , getContext('#set($foo = $a > $b)', {a: 1, b: 2}).foo)
assert.equal(false , getContext('#set($foo = $a && $b)', {a: 1, b: 0}).foo)
assert.equal(true , getContext('#set($foo = $a || $b)', {a: 1, b: 0}).foo)
it('expression logic', function() {
assert.equal(false, getContext('#set($foo = 10 == 11 && 3 > 1)').foo)
assert.equal(true, getContext('#set($foo = 10 < 11 && 3 > 1)').foo)
assert.equal(true, getContext('#set($foo = 10 > 11 || 3 > 1)').foo)
assert.equal(true, getContext('#set($foo = !(10 > 11) && 3 > 1)').foo)
assert.equal(false, getContext('#set($foo = $a > $b)', {a: 1, b: 2}).foo)
assert.equal(false, getContext('#set($foo = $a && $b)', {a: 1, b: 0}).foo)
assert.equal(true, getContext('#set($foo = $a || $b)', {a: 1, b: 0}).foo)
})
it('#set context should be global, #25', function(){
it('#set context should be global, #25', function() {
var vm = '#macro(local) #set($val =1) $val #end #local() $val'

@@ -308,6 +306,6 @@ var ret = render(vm).replace(/\s+/g, '')

describe('Literals', function(){
describe('Literals', function() {
it("eval string value", function(){
var vm = '#set( $directoryRoot = "www" )' +
it("eval string value", function() {
var vm = '#set( $directoryRoot = "www" )' +
'#set( $templateName = "index.vm")' +

@@ -320,3 +318,3 @@ '#set( $template = "$directoryRoot/$templateName" )' +

it('not eval string', function(){
it('not eval string', function() {
var vm = "#set( $blargh = '$foo' )$blargh"

@@ -326,3 +324,3 @@ assert.equal('$foo', render(vm))

it('not parse #[[ ]]#', function(){
it('not parse #[[ ]]#', function() {
var vm = '#foreach ($woogie in $boogie) nothing to $woogie #end'

@@ -332,3 +330,3 @@ assert.equal(vm, render('#[[' + vm + ']]#'))

it('Range Operator', function(){
it('Range Operator', function() {
var vm1 = '#set($foo = [-1..2])'

@@ -343,3 +341,3 @@ var vm2 = '#set($foo = [-1..$bar])'

it('map and array nest', function(){
it('map and array nest', function() {
var vm1 = '' +

@@ -362,9 +360,13 @@ '#set($a = [\n' +

assert.deepEqual([{name: 1}, { name: 2 }], getContext(vm1).a)
assert.deepEqual({a: [1, 2, ["1", "a"], {a: 1}], b: "12", d: null, c: false}, getContext(vm2).a)
var expected = {
a: [1, 2, ["1", "a"], {a: 1}],
b: "12", d: null, c: false
};
assert.deepEqual(expected, getContext(vm2).a)
})
})
describe('Conditionals', function(){
describe('Conditionals', function() {
it('#if', function(){
it('#if', function() {
var vm = '#if($foo)Velocity#end'

@@ -374,3 +376,3 @@ assert.equal('Velocity', render(vm, {foo: 1}))

it('#if not work', function(){
it('#if not work', function() {
var vm = '#if($!css_pureui)hello world#end'

@@ -380,10 +382,11 @@ assert.equal('', render(vm))

it('#elseif & #else', function(){
var vm = '#if($foo < 5)Go North#elseif($foo == 8)Go East#{else}Go South#end'
assert.equal('Go North' , render(vm, {foo: 4}))
assert.equal('Go East' , render(vm, {foo: 8}))
assert.equal('Go South' , render(vm, {foo: 9}))
it('#elseif & #else', function() {
var vm = '#if($foo < 5)Go North#elseif($foo == 8)' +
'Go East#{else}Go South#end'
assert.equal('Go North', render(vm, {foo: 4}))
assert.equal('Go East', render(vm, {foo: 8}))
assert.equal('Go South', render(vm, {foo: 9}))
})
it('#if with arguments', function(){
it('#if with arguments', function() {
var vm = '#if($foo.isTrue(true))true#end'

@@ -401,5 +404,5 @@ var foo = {

describe('Loops', function(){
describe('Loops', function() {
it('#foreach', function(){
it('#foreach', function() {
var vm = '#foreach( $product in $allProducts )<li>$product</li>#end'

@@ -410,3 +413,3 @@ var data = {allProducts: ["book", "phone"]}

it('#foreach with map', function(){
it('#foreach with map', function() {
var vm = '#foreach($key in $products) name => $products.name #end'

@@ -417,4 +420,5 @@ var data = {products: {name: "hanwen"}}

it('#foreach with map keySet', function(){
var vm = '#foreach($key in $products.keySet()) $key => $products.get($key) #end'
it('#foreach with map keySet', function() {
var vm = '#foreach($key in $products.keySet())' +
' $key => $products.get($key) #end'
var data = {products: {name: "hanwen"}}

@@ -424,4 +428,5 @@ assert.equal(' name => hanwen ', render(vm, data))

it('#foreach with nest foreach', function(){
var vm = '#foreach($i in [1..2])${velocityCount}#foreach($j in [2..3])${velocityCount}#end#end'
it('#foreach with nest foreach', function() {
var vm = '#foreach($i in [1..2])${velocityCount}' +
'#foreach($j in [2..3])${velocityCount}#end#end'
assert.equal('112212', render(vm))

@@ -432,24 +437,24 @@ var vm = '#foreach($i in [5..2])$i#end'

it('#foreach with map entrySet', function(){
it('#foreach with map entrySet', function() {
var vm = '' +
'#set($js_file = {\n' +
' "js_arale":"build/js/arale.js?t=20110608",\n'+
' "js_ma_template":"build/js/ma/template.js?t=20110608",\n'+
' "js_pa_pa":"build/js/pa/pa.js?t=20110608",\n'+
' "js_swiff":"build/js/app/swiff.js?t=20110608",\n' +
' "js_alieditControl":"build/js/pa/alieditcontrol-update.js?t=20110608"\n' +
'})\n' +
'#foreach($_item in $js_file.entrySet())'+
'$_item.key = $staticServer.getURI("/${_item.value}")\n'+
'#end'
'#set($js_file = {\n' +
' "js_arale":"build/js/arale.js?t=20110608",\n' +
' "js_ma_template":"build/js/ma/template.js?t=20110608",\n' +
' "js_pa_pa":"build/js/pa/pa.js?t=20110608",\n' +
' "js_swiff":"build/js/app/swiff.js?t=20110608",\n' +
' "js_alieditControl":"build/js/pa/alieditcontrol-update.js?"\n' +
'})\n' +
'#foreach($_item in $js_file.entrySet())' +
'$_item.key = $staticServer.getURI("/${_item.value}")\n' +
'#end'
var ret = 'js_arale = /path/build/js/arale.js?t=20110608\n' +
'js_ma_template = /path/build/js/ma/template.js?t=20110608\n' +
'js_pa_pa = /path/build/js/pa/pa.js?t=20110608\n' +
'js_swiff = /path/build/js/app/swiff.js?t=20110608\n' +
'js_alieditControl = /path/build/js/pa/alieditcontrol-update.js?t=20110608\n'
'js_ma_template = /path/build/js/ma/template.js?t=20110608\n' +
'js_pa_pa = /path/build/js/pa/pa.js?t=20110608\n' +
'js_swiff = /path/build/js/app/swiff.js?t=20110608\n' +
'js_alieditControl = /path/build/js/pa/alieditcontrol-update.js?\n'
var data = {
staticServer: {
getURI: function(url){
getURI: function(url) {
return '/path' + url

@@ -464,4 +469,5 @@ }

it('#foreach with #macro, $velocityCount should work find, #25', function(){
var vm = '#macro(local) #end #foreach ($one in [1,2,4]) #local() $velocityCount #end'
it('#foreach with #macro, $velocityCount should work, #25', function() {
var vm = '#macro(local) #end ' +
'#foreach ($one in [1,2,4]) #local() $velocityCount #end'
var ret = render(vm).replace(/\s+/g, '')

@@ -471,4 +477,5 @@ assert.equal('123', ret)

it('#break', function(){
var vm = '#foreach($num in [1..6]) #if($foreach.count > 3) #break #end $num #end'
it('#break', function() {
var vm = '#foreach($num in [1..6])' +
' #if($foreach.count > 3) #break #end $num #end'
assert.equal(' 1 2 3 4 ', render(vm))

@@ -479,5 +486,5 @@ })

describe('Velocimacros', function(){
describe('Velocimacros', function() {
it('simple #macro', function(){
it('simple #macro', function() {
var vm = '#macro( d )<tr><td></td></tr>#end #d()'

@@ -487,3 +494,3 @@ assert.equal(' <tr><td></td></tr>', render(vm))

it('compex #macro', function(){
it('compex #macro', function() {
var vm = '#macro( d $name)<tr><td>$!name</td></tr>#end #d($foo)'

@@ -493,9 +500,9 @@ var vm1 = '#macro( d $a $b)#if($b)$a#end#end #d ( $foo $bar )'

assert.equal(' <tr><td>hanwen</td></tr>', render(vm, {foo: 'hanwen'}))
assert.equal(' <tr><td></td></tr>' , render(vm))
assert.equal(' ' , render(vm1, {foo: "haha"}))
assert.equal(' ' , render(vm1, {foo: "haha", bar: false}))
assert.equal(' haha' , render(vm1, {foo: "haha", bar: true}))
assert.equal(' <tr><td></td></tr>', render(vm))
assert.equal(' ', render(vm1, {foo: "haha"}))
assert.equal(' ', render(vm1, {foo: "haha", bar: false}))
assert.equal(' haha', render(vm1, {foo: "haha", bar: true}))
})
it('#macro call arguments', function(){
it('#macro call arguments', function() {
var vm = '#macro( d $a $b $d)$a$b$!d#end #d ( $foo , $bar, $dd )'

@@ -506,8 +513,9 @@ assert.equal(' ab', render(vm, {foo: 'a', bar: 'b'}))

it('#macro map argument', function(){
var vm = '#macro( d $a)#foreach($_item in $a.entrySet())$_item.key = $_item.value #end#end #d ( {"foo": $foo,"bar":$bar} )'
it('#macro map argument', function() {
var vm = '#macro( d $a)#foreach($_item in $a.entrySet())' +
'$_item.key = $_item.value #end#end #d ( {"foo": $foo,"bar":$bar} )'
assert.equal(' foo = a bar = b ', render(vm, {foo: 'a', bar: 'b'}))
})
it('#noescape', function(){
it('#noescape', function() {
var vm = '#noescape()$hello#end'

@@ -519,4 +527,4 @@ assert.equal('hello world', render(vm, {hello: 'hello world'}))

describe('Escaping', function(){
it('escape slash', function(){
describe('Escaping', function() {
it('escape slash', function() {
var vm = '#set( $email = "foo" )$email \\$email'

@@ -526,3 +534,3 @@ assert.equal('foo $email', render(vm))

it('double slash', function(){
it('double slash', function() {
var vm = '#set( $email = "foo" )\\\\$email \\\\\\$email'

@@ -534,5 +542,5 @@ assert.equal("\\foo \\$email", render(vm))

describe('Error condiction', function(){
describe('Error condiction', function() {
it('css color render', function(){
it('css color render', function() {
var vm = 'color: #666 height: 39px'

@@ -542,8 +550,8 @@ assert.equal(vm, render(vm))

it('jquery parse', function(){
var vm = '$(function(){ $("a").click() $.post() })'
it('jquery parse', function() {
var vm = '$(function() { $("a").click() $.post() })'
assert.equal(vm, render(vm))
})
it('issue #7: $ meet with #', function(){
it('issue #7: $ meet with #', function() {
var vm = '$bar.foo()#if(1>0)...#end'

@@ -553,9 +561,14 @@ assert.equal('$bar.foo()...', render(vm))

it('issue #15', function(){
var vm = '#macro(a $b $list)#foreach($a in $list)${a}#end $b #end #a("hello", [1, 2])'
it('issue #15', function() {
var vm = '#macro(a $b $list)' +
'#foreach($a in $list)${a}#end $b #end #a("hello", [1, 2])'
assert.equal(' 12 hello ', render(vm))
})
it('issue #18', function(){
var vm = '$!tradeDetailModel.goodsInfoModel.goodsTitle[<a href="$!personalModule.setTarget(\'/p.htm\').addQueryData("id",$!stringUtil.substringAfter($!tradeDetailModel.goodsInfoModel.goodsId,"guarantee."))" target="_blank">商品页面</a>]'
it('issue #18', function() {
var vm = '$!tradeDetailModel.goodsInfoModel.goodsTitle' +
'[<a href="$!personalModule.setTarget(\'/p.htm\')' +
'.addQueryData("id",$!stringUtil.substringAfter' +
'($!tradeDetailModel.goodsInfoModel.goodsId,"guarantee."))"' +
' target="_blank">商品页面</a>]'
var ret = '[<a href="" target="_blank">商品页面</a>]'

@@ -565,3 +578,3 @@ assert.equal(ret, render(vm))

it('issue #18, condiction 2', function(){
it('issue #18, condiction 2', function() {
var vm = '$!a(**** **** **** $stringUtil.right($!b,4))'

@@ -572,3 +585,3 @@ var ret = '(**** **** **** $stringUtil.right($!b,4))'

it('# meet with css property', function(){
it('# meet with css property', function() {
var vm = '#margin-top:2px'

@@ -578,3 +591,3 @@ assert.equal(vm, render(vm))

it('var end must in condiction var begin', function(){
it('var end must in condiction var begin', function() {
var vm = 'stepFareNo:{$!result.getStepFareNo()}'

@@ -584,3 +597,3 @@ assert.equal('stepFareNo:{}', render(vm))

it('empty string condiction', function(){
it('empty string condiction', function() {
assert.equal('', render(''))

@@ -594,18 +607,17 @@ assert.equal('', render('##hello'))

describe('throw friendly error message', function() {
it('print right posiont when error throw', function(){
it('print right posiont when error throw', function() {
var vm = '111\nsdfs\n$foo($name)'
var expected = '<i>'
var compile = new Compile(Parser.parse(vm), { escape: false })
var compile = new Compile(parse(vm), { escape: false })
var context = {
name: '<i>',
foo: function(name){
foo: function() {
throw new Error('Run error')
}
}
assert.throws(function(){
assert.throws(function() {
compile.render(context)
}, /\$foo\(\$name\)/)
assert.throws(function(){
assert.throws(function() {
compile.render(context)

@@ -615,3 +627,3 @@ }, /L\/N 3:0/)

it('print error stack of user-defined macro', function(){
it('print error stack of user-defined macro', function() {
var vm = '111\n\n#foo($name)'

@@ -621,8 +633,8 @@ var vm1 = '\nhello#parse("vm.vm")'

var compile = new Compile(Parser.parse('\n\n#parse("vm1.vm")'))
var compile = new Compile(parse('\n\n#parse("vm1.vm")'))
var macros = {
foo: function(name){
foo: function() {
throw new Error('Run error')
},
parse: function(name){
parse: function(name) {
return this.eval(files[name]);

@@ -632,17 +644,11 @@ }

var expected = [
'Run error\n',
'at #foo($name) L/N 3:0' ,
'tests/compile.js',
'at #parse("vm.vm") L/N 2:5' ,
'at #parse("vm1.vm") L/N 3:0'
];
var expected = '' +
'Run error\n' +
' at #foo($name) L/N 3:0\n' +
' at #parse("vm.vm") L/N 2:5\n' +
' at #parse("vm1.vm") L/N 3:0';
try {
compile.render({}, macros)
} catch(e) {
console.log(e.message);
expected.forEach(function(msg){
assert.ok(e.message.indexOf(msg) > -1);
});
} catch (e) {
assert.equal(expected, e.message);
}

@@ -652,7 +658,7 @@ })

describe('user-defined macro, such as #include, #parse', function(){
describe('user-defined macro, such as #include, #parse', function() {
it('basic', function(){
it('basic', function() {
var macros = {
haha: function(a, b){
haha: function(a, b) {
a = a || ''

@@ -669,11 +675,8 @@ b = b || ''

it('use eval', function(){
//这一句非常重要,在node端无需处理,web端必须如此声明
Compile.Parser = Parser
it('use eval', function() {
var macros = {
cmsparse: function(str){
cmsparse: function(str) {
return this.eval(str)
},
d: function(){
d: function() {
return 'I am d!'

@@ -692,21 +695,19 @@ }

it('use eval with local variable', function(){
//这一句非常重要,在node端无需处理,web端必须如此声明
Compile.Parser = Parser
it('use eval with local variable', function() {
var macros = {
cmsparse: function(str){
cmsparse: function() {
return macros.include.apply(this, arguments)
},
include: function(str){
include: function(str) {
return this.eval(str, {name: "hanwen"})
},
parse: function(file){
parse: function(file) {
return file
},
d: function($name){
d: function() {
return this.eval('I am $name!')

@@ -728,8 +729,5 @@ }

it('eval work with #set', function(){
//这一句非常重要,在node端无需处理,web端必须如此声明
Compile.Parser = Parser
it('eval work with #set', function() {
var macros = {
cmsparse: function(str){
cmsparse: function(str) {
return this.eval(str)

@@ -741,3 +739,4 @@ }

var o = {
str: '#set($foo = ["hello"," ", "world"])#foreach($word in $foo)$word#end'
str: '#set($foo = ["hello"," ", "world"])' +
'#foreach($word in $foo)$word#end'
}

@@ -752,7 +751,7 @@

it('$control.setTemplate', function(){
it('$control.setTemplate', function() {
var control = {
setTemplate: function(vm){
setTemplate: function(vm) {

@@ -763,7 +762,7 @@ this.vm = vm;

},
toString: function(){
toString: function() {
return this.eval(this.vm, this.__temp);
},
__temp: {},
setParameter: function(key, value){
setParameter: function(key, value) {
this.__temp[key] = value;

@@ -776,4 +775,6 @@ return this;

var vm = '$control.setTemplate($str).setParameter("who", "Blob").setParameter("where", "China")'
assert.equal(render(vm, {str: str, control: control}), 'hello Blob, welcome to China')
var vm = '$control.setTemplate($str).setParameter("who", "Blob")' +
'.setParameter("where", "China")'
var expected = 'hello Blob, welcome to China';
assert.equal(render(vm, {str: str, control: control}), expected)

@@ -786,3 +787,4 @@ })

it('#29', function() {
var vm = '#set($total = 0) #foreach($i in [1,2,3]) #set($total = $total + $i) #end $total'
var vm = '#set($total = 0) #foreach($i in [1,2,3])' +
' #set($total = $total + $i) #end $total'
assert.equal(render(vm).trim(), "6")

@@ -796,4 +798,4 @@ })

describe('multiline', function(){
it('#set multiline', function(){
describe('multiline', function() {
it('#set multiline', function() {
var vm = "$bar.foo()\n#set($foo=$bar)\n..."

@@ -803,3 +805,3 @@ assert.equal("$bar.foo()\n...", render(vm))

it('#if multiline', function(){
it('#if multiline', function() {
var vm = "$bar.foo()\n#if(1>0)\n...#end"

@@ -809,3 +811,3 @@ assert.equal("$bar.foo()\n...", render(vm))

it('#set #set', function(){
it('#set #set', function() {
var vm = "$bar.foo()\n...\n#set($foo=$bar)\n#set($foo=$bar)"

@@ -815,3 +817,3 @@ assert.equal("$bar.foo()\n...\n", render(vm))

it('#if multiline #set', function(){
it('#if multiline #set', function() {
var vm = "$bar.foo()\n#if(1>0)\n#set($foo=$bar)\n...#end"

@@ -821,3 +823,3 @@ assert.equal("$bar.foo()\n...", render(vm))

it('#if multiline #set #end', function(){
it('#if multiline #set #end', function() {
var vm = "$bar.foo()\n#if(1>0)...\n#set($foo=$bar)\n#end"

@@ -827,4 +829,4 @@ assert.equal("$bar.foo()\n...\n", render(vm))

it('with references', function(){
var vm = [ 'a',
it('with references', function() {
var vm = ['a',
'#foreach($b in $nums)',

@@ -837,8 +839,9 @@ '#if($b) ',

'c'].join("\n");
var expected = [ 'a', 'b', 'e 1', 'b', 'e 2', 'b', 'e 3', 'c'].join("\n")
var expected = ['a', 'b', 'e 1', 'b', 'e 2', 'b', 'e 3', 'c'].join("\n")
assert.equal(expected, render(vm, {nums:[{alm:1},{alm:2},{alm:3}],bar:""}))
var data = {nums:[{alm:1}, {alm:2}, {alm:3}], bar:""};
assert.equal(expected, render(vm, data))
})
it('multiple newlines after statement', function(){
it('multiple newlines after statement', function() {
var vm = '#if(1>0)\n\nb#end'

@@ -849,10 +852,9 @@ assert.equal('\nb', render(vm))

describe('define support', function(){
it('basic', function(){
var vm = '#define( $block )\nHello $who#end\n#set( $who = "World!" )\n$block'
describe('define support', function() {
it('basic', function() {
var vm = '#define($block)\nHello $who#end\n#set($who = "World!")\n$block'
assert.equal('Hello World!', render(vm))
})
})
})

@@ -0,7 +1,8 @@

'use strict';
var Velocity = require('../src/velocity')
var assert = require("assert")
describe('Helper', function(){
describe('Helper', function() {
var getRefText = Velocity.Helper.getRefText
var parse = Velocity.Parser.parse
var parse = Velocity.parse
describe('getRefText', function() {

@@ -8,0 +9,0 @@ it('simple reference', function() {

@@ -1,11 +0,20 @@

var Parser = require('../src/velocity').Parser
'use strict';
var parse = require('../src/velocity').parse
var assert = require("assert")
describe('Parser', function(){
describe('Parser', function() {
describe('simple references', function(){
describe('simple references', function() {
it('simple references', function(){
it('self define block', function() {
var vm = '#cms(1)<div class="abs-right"> #H(1,"第一个链接") </div> #end';
var ast = parse(vm, { cms: true });
assert(ast.length, 1);
assert(ast[0][0].type, 'cms');
console.log(ast[0][0])
});
it('simple references', function() {
var vm = 'hello world: $foo'
var ret = Parser.parse(vm)
var ret = parse(vm)

@@ -16,13 +25,12 @@ assert.ok(ret instanceof Array)

assert.equal('foo', ret[1].id)
})
it('valid variable references', function(){
it('valid variable references', function() {
var vm = '$mud-Slinger_1'
assert.equal('mud-Slinger_1', Parser.parse(vm)[0].id)
assert.equal('mud-Slinger_1', parse(vm)[0].id)
})
it('wraped references', function(){
it('wraped references', function() {
var vm = '${mudSlinger}'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]
assert.equal(true, ast.isWraped)

@@ -32,4 +40,4 @@ assert.equal('mudSlinger', ast.id)

it('function call references', function(){
var ast = Parser.parse('$foo()')[0]
it('function call references', function() {
var ast = parse('$foo()')[0]
assert.equal(false, ast.args)

@@ -41,13 +49,13 @@ assert.equal('references', ast.type)

describe('Properties', function(){
describe('Properties', function() {
it('simple property', function(){
it('simple property', function() {
var vm = '$customer.Address'
var asts = Parser.parse(vm)
var asts = parse(vm)
assert.deepEqual(asts[0], {
id : "customer",
prue : true,
type : "references",
path : [{"type": "property","id": "Address"}],
leader : '$',
id: "customer",
prue: true,
type: "references",
path: [{type: 'property', id: 'Address'}],
leader: '$',
pos: { first_line: 1, last_line: 1, first_column: 0, last_column: 17 }

@@ -59,25 +67,25 @@ })

describe('Methods ', function(){
describe('Methods ', function() {
it('with no arguments', function(){
it('with no arguments', function() {
var vm = '$foo.bar()'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]
assert.deepEqual(ast['path'], [{
type : "method",
id : "bar",
args : false
type: "method",
id: "bar",
args: false
}])
})
it('with arguments integer', function(){
it('with arguments integer', function() {
var vm = '$foo.bar(10)'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]
assert.deepEqual(ast['path'], [{
type : "method",
id : "bar",
args : [{
type : "integer",
value : "10"
type: "method",
id: "bar",
args: [{
type: "integer",
value: "10"
}]

@@ -87,5 +95,5 @@ }])

it('with arguments references', function(){
it('with arguments references', function() {
var vm = '$foo.bar($bar)'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]

@@ -95,5 +103,5 @@ assert.equal(ast.prue, true)

assert.deepEqual(ast.path[0].args, [{
type : "references",
leader : "$",
id : "bar"
type: "references",
leader: "$",
id: "bar"
}])

@@ -104,12 +112,12 @@ })

describe('Index', function(){
describe('Index', function() {
it('all kind of indexs', function(){
it('all kind of indexs', function() {
var vm = '$foo[0] $foo[$i] $foo["bar"]'
var asts = Parser.parse(vm)
var asts = parse(vm)
assert.equal(5, asts.length)
//asts[0].path[0] => $foo[0]
//{type: 'index', id: {type: 'integer', value: '0'}}
// asts[0].path[0] => $foo[0]
// {type: 'index', id: {type: 'integer', value: '0'}}
assert.equal('index', asts[0].path[0].type)

@@ -119,4 +127,4 @@ assert.equal('integer', asts[0].path[0].id.type)

//asts[2].path[0] => $foo[$i]
//{type: 'references', id: {type:'references', id: 'i', leader: '$'}}
// asts[2].path[0] => $foo[$i]
// {type: 'references', id: {type:'references', id: 'i', leader: '$'}}
assert.equal('index', asts[2].path[0].type)

@@ -126,4 +134,4 @@ assert.equal('references', asts[2].path[0].id.type)

//asts[4].path[0] => $foo["bar"]
//{type: 'index', id: {type: 'string', value: 'bar', isEval: true}}
// asts[4].path[0] => $foo["bar"]
// {type: 'index', id: {type: 'string', value: 'bar', isEval: true}
assert.equal('index', asts[4].path[0].type)

@@ -137,7 +145,7 @@ assert.equal('string', asts[4].path[0].id.type)

describe('complex references', function(){
describe('complex references', function() {
it('property + index + property', function(){
it('property + index + property', function() {
var vm = '$foo.bar[1].junk'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]

@@ -156,5 +164,5 @@ assert.equal('foo', ast.id)

it('method + index', function(){
it('method + index', function() {
var vm = '$foo.callMethod()[1]'
var ast = Parser.parse(vm)[0]
var ast = parse(vm)[0]

@@ -172,5 +180,5 @@ assert.equal(2, ast.path.length)

it('property should not start with alphabet', function(){
var asts = Parser.parse('$foo.124')
var ast2 = Parser.parse('$foo.-24')[0]
it('property should not start with alphabet', function() {
var asts = parse('$foo.124')
var ast2 = parse('$foo.-24')[0]

@@ -185,5 +193,5 @@ assert.equal(3, asts.length)

it('index should end with close bracket', function(){
assert.throws(function(){
Parser.parse("$foo.bar['a'12]")
it('index should end with close bracket', function() {
assert.throws(function() {
parse("$foo.bar['a'12]")
}, /Parse error/)

@@ -194,7 +202,7 @@ })

describe('Directives', function(){
describe('Directives', function() {
it('#macro', function(){
it('#macro', function() {
var vm = '#macro( d $a $b)#if($b)$a#end#end #d($foo $bar)'
var asts = Parser.parse(vm)
var asts = parse(vm)

@@ -217,6 +225,6 @@ var ifAst = asts[0][1]

describe('comment identify', function(){
describe('comment identify', function() {
it('one line comment', function(){
var asts = Parser.parse('#set( $monkey.Number = 123)##number literal')
it('one line comment', function() {
var asts = parse('#set( $monkey.Number = 123)##number literal')

@@ -223,0 +231,0 @@ assert.equal(2, asts.length)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc