feature: interpolate bracket access, close #14

This commit is contained in:
harttle
2016-10-25 01:46:37 +08:00
parent 6d20f7aa8e
commit 6135028015
8 changed files with 851 additions and 750 deletions
+591 -615
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "shopify-liquid", "name": "shopify-liquid",
"version": "1.2.5", "version": "1.3.0",
"description": "Liquid template engine for JavaScript, Node.js and Browser", "description": "Liquid template engine for JavaScript, Node.js and Browser",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
+6 -1
View File
@@ -34,6 +34,7 @@ var numberLine = new RegExp(`^${number.source}$`);
var boolLine = new RegExp(`^${bool.source}$`, 'i'); var boolLine = new RegExp(`^${bool.source}$`, 'i');
var quotedLine = new RegExp(`^${quoted.source}$`); var quotedLine = new RegExp(`^${quoted.source}$`);
var rangeLine = new RegExp(`^${rangeCapture.source}$`); var rangeLine = new RegExp(`^${rangeCapture.source}$`);
var integerLine = new RegExp(`^${integer.source}$`);
// filter related // filter related
var valueList = new RegExp(`${value.source}(\\s*,\\s*${value.source})*`); var valueList = new RegExp(`${value.source}(\\s*,\\s*${value.source})*`);
@@ -47,6 +48,10 @@ var operators = [
/==|!=|<=|>=|<|>|\s+contains\s+/ /==|!=|<=|>=|<|>|\s+contains\s+/
]; ];
function isInteger(str){
return integerLine.test(str);
}
function isLiteral(str) { function isLiteral(str) {
return literalLine.test(str); return literalLine.test(str);
} }
@@ -82,5 +87,5 @@ module.exports = {
range, rangeCapture, range, rangeCapture,
identifier, value, quoteBalanced, operators, identifier, value, quoteBalanced, operators,
quotedLine, numberLine, boolLine, rangeLine, literalLine, filterLine, tagLine, quotedLine, numberLine, boolLine, rangeLine, literalLine, filterLine, tagLine,
isLiteral, isVariable, parseLiteral, isRange, matchValue isLiteral, isVariable, parseLiteral, isRange, matchValue, isInteger
}; };
+147 -69
View File
@@ -1,79 +1,157 @@
const _ = require('./util/underscore.js'); const _ = require('./util/underscore.js');
const lexical = require('./lexical.js');
var Scope = { var Scope = {
safeGet: function(str) { safeGet: function(str) {
var i; var i;
// get all // get all
if (str === undefined) { if (str === undefined) {
var ctx = {}; var ctx = {};
for (i = this.scopes.length - 1; i >= 0; i--) { for (i = this.scopes.length - 1; i >= 0; i--) {
var scp = this.scopes[i]; var scp = this.scopes[i];
for (var k in scp) { for (var k in scp) {
if (scp.hasOwnProperty(k)) { if (scp.hasOwnProperty(k)) {
ctx[k] = scp[k]; ctx[k] = scp[k];
} }
} }
} }
return ctx; return ctx;
} }
// get one path // get one path
for (i = this.scopes.length - 1; i >= 0; i--) { for (i = this.scopes.length - 1; i >= 0; i--) {
var v = getPropertyByPath(this.scopes[i], str); var v = this.getPropertyByPath(this.scopes[i], str);
if (v !== undefined) return v; if (v !== undefined) return v;
} }
}, },
get: function(str) { get: function(str) {
var val = this.safeGet(str); var val = this.safeGet(str);
if (val === undefined && this.opts.strict) { if (val === undefined && this.opts.strict) {
throw new Error(`[strict_variables] undefined variable: ${str}`); throw new Error(`[strict_variables] undefined variable: ${str}`);
} }
return val; return val;
}, },
set: function(k, v) { set: function(k, v) {
setPropertyByPath(this.scopes[this.scopes.length - 1], k, v); this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
return this; return this;
}, },
push: function(ctx) { push: function(ctx) {
if (!ctx) throw new Error(`trying to push ${ctx} into scopes`); if (!ctx) throw new Error(`trying to push ${ctx} into scopes`);
return this.scopes.push(ctx); return this.scopes.push(ctx);
}, },
pop: function() { pop: function() {
return this.scopes.pop(); return this.scopes.pop();
} },
setPropertyByPath: function(obj, path, val) {
if (_.isString(path)) {
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
for (var i = 0; i < paths.length; i++) {
var key = paths[i];
if (i === paths.length - 1) {
return obj[key] = val;
}
if (undefined === obj[key]) obj[key] = {};
// case for readonly objects
obj = obj[key] || {};
}
return obj;
}
return obj[path] = val;
},
getPropertyByPath: function(obj, path) {
if (_.isString(path) && path.length) {
var paths = this.propertyAccessSeq(path);
paths.forEach(p => obj = obj && obj[p]);
return obj;
}
return obj[path];
},
/*
* Parse property access sequence from access string
* @example
* accessSeq("foo.bar") // ['foo', 'bar']
* accessSeq("foo['bar']") // ['foo', 'bar']
* accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function(str) {
var seq = [],
name = '';
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name);
name = '';
var delemiter = str[i + 1];
// foo[bar.coo]
if (delemiter !== "'" && delemiter !== '"') {
var j = matchRightBracket(str, i + 1);
if (j === -1) {
throw new Error(`unbalanced []: ${str}`);
}
name = str.slice(i + 1, j);
// foo[1]
if(lexical.isInteger(name)){
seq.push(name);
}
// foo["bar"]
else{
seq.push(this.get(name));
}
name = '';
i = j;
}
// foo["bar"]
else {
var j = str.indexOf(delemiter, i + 2);
if (j === -1) {
throw new Error(`unbalanced ${delemiter}: ${str}`);
}
name = str.slice(i + 2, j);
seq.push(name);
name = '';
i = j + 1;
}
}
// foo.bar
else if (str[i] === ".") {
seq.push(name);
name = '';
}
//foo.bar
else {
name += str[i];
}
}
if (name.length) seq.push(name);
return seq;
}
}; };
function setPropertyByPath(obj, path, val) { function matchRightBracket(str, begin) {
if (_.isString(path)) { var stack = 1; // count of '[' - count of ']'
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'); for (var i = begin; i < str.length; i++) {
for (var i = 0; i < paths.length; i++) { if (str[i] === '[') {
var key = paths[i]; stack++;
if (i === paths.length - 1) { }
return obj[key] = val; if (str[i] === ']') {
} stack--;
if (undefined === obj[key]) obj[key] = {}; if (stack === 0) {
// case for readonly objects return i;
obj = obj[key] || {}; }
} }
return obj; }
} return -1;
return obj[path] = val;
}
function getPropertyByPath(obj, path) {
if (_.isString(path)) {
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
paths.forEach(p => obj = obj && obj[p]);
return obj;
}
return obj[path];
} }
exports.factory = function(_ctx, opts) { exports.factory = function(_ctx, opts) {
opts = opts || {}; opts = opts || {};
opts.strict = opts.strict || false; opts.strict = opts.strict || false;
var scope = Object.create(Scope); var scope = Object.create(Scope);
scope.opts = opts; scope.opts = opts;
scope.scopes = [_ctx || {}]; scope.scopes = [_ctx || {}];
return scope; return scope;
}; };
+1 -1
View File
@@ -40,7 +40,7 @@ module.exports = function(liquid) {
liquid.registerTag('block', { liquid.registerTag('block', {
parse: function(token, remainTokens){ parse: function(token, remainTokens){
var match = /\w+/.exec(token.args); var match = /\w+/.exec(token.args);
this.block = match ? match[0] : ''; this.block = match ? match[0] : 'anonymous';
this.tpls = []; this.tpls = [];
var p, stream = liquid.parser.parseStream(remainTokens) var p, stream = liquid.parser.parseStream(remainTokens)
+101 -56
View File
@@ -4,69 +4,114 @@ const expect = chai.expect;
var Scope = require('../src/scope.js'); var Scope = require('../src/scope.js');
describe('scope', function() { describe('scope', function() {
var scope, ctx; var scope, ctx;
beforeEach(function() { beforeEach(function() {
ctx = { ctx = {
foo: 'bar' foo: 'zoo',
}; bar: {
scope = Scope.factory(ctx); zoo: 'coo',
}); "Mr.Smith": 'John',
arr: ['a', 'b']
}
};
scope = Scope.factory(ctx);
});
it('should get direct property', function() { describe('#propertyAccessSeq()', function() {
expect(scope.get('foo')).equal('bar'); it('should handle dot syntax', function() {
}); expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<String>] syntax', function() {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<Identifier>] syntax', function() {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo']);
});
it('should handle nested access', function() {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']);
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']);
});
});
it('should get undefined property', function() { describe('#get()', function() {
function fn() { it('should get direct property', function() {
scope.get('notdefined'); expect(scope.get('foo')).equal('zoo');
} });
expect(fn).to.not.throw();
expect(scope.get('notdefined')).to.equal(undefined);
expect(scope.get('')).to.equal(undefined);
expect(scope.get(false)).to.equal(undefined);
});
it('should throw undefined in strict mode', function() { it('should get undefined property', function() {
scope = Scope.factory(ctx, { function fn() {
strict: true scope.get('notdefined');
}); }
expect(fn).to.not.throw();
expect(scope.get('notdefined')).to.equal(undefined);
expect(scope.get('')).to.equal(undefined);
expect(scope.get(false)).to.equal(undefined);
});
function fn() { it('should throw undefined in strict mode', function() {
scope.get('notdefined'); scope = Scope.factory(ctx, {
} strict: true
expect(fn).to.throw(/undefined variable: notdefined/); });
});
it('should get all properties when arguments empty', function() { function fn() {
expect(scope.get()).deep.equal(ctx); scope.get('notdefined');
}); }
expect(fn).to.throw(/undefined variable: notdefined/);
});
it('should access child property via dot syntax', function() { it('should get all properties when arguments empty', function() {
scope.set('oo.bar', 'FOO'); expect(scope.get()).deep.equal(ctx);
expect(scope.get('oo.bar')).to.equal('FOO'); });
});
it('should access child property via [<Number>] syntax', function() { it('should access child property via dot syntax', function() {
scope.set('bar', ['a', {'b': [1,2]}]); expect(scope.get('bar.zoo')).to.equal('coo');
expect(scope.get('bar[0]')).to.equal('a'); expect(scope.get('bar.arr')).to.deep.equal(['a', 'b']);
expect(scope.get('bar[1].b')).to.deep.equal([1, 2]); });
expect(scope.get('bar[1].b[1]')).to.equal(2);
});
it('should push scope', function() { it('should access child property via [<String>] syntax', function() {
scope.set('bar', 'bar'); expect(scope.get('bar["zoo"]')).to.equal('coo');
scope.push({ });
foo: 'foo'
});
expect(scope.get('foo')).to.equal('foo');
expect(scope.get('bar')).to.equal('bar');
});
it('should pop scope', function() { it('should access child property via [<Number>] syntax', function() {
scope.push({ expect(scope.get('bar.arr[0]')).to.equal('a');
foo: 'foo' });
});
scope.pop(); it('should access child property via [<Identifier>] syntax', function() {
expect(scope.get('foo')).to.equal('bar'); expect(scope.get('bar[foo]')).to.equal('coo');
}); });
it('should support nested case', function() {
scope.set('posts', {
"first": {"name": "A Nice Day"}
});
scope.set('category', {
"diary": ["first"]
});
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day');
});
});
describe('.push(), .pop()', function() {
it('should push scope', function() {
scope.set('bar', 'bar');
scope.push({
foo: 'foo'
});
expect(scope.get('foo')).to.equal('foo');
expect(scope.get('bar')).to.equal('bar');
});
it('should pop scope', function() {
scope.push({
foo: 'foo'
});
scope.pop();
expect(scope.get('foo')).to.equal('zoo');
});
});
}); });
+3 -5
View File
@@ -13,8 +13,7 @@ describe('expression', function() {
scope = Scope.factory({ scope = Scope.factory({
one: 1, one: 1,
two: 2, two: 2,
x: 'XXX', x: 'XXX'
z: 'z'
}); });
}); });
@@ -41,7 +40,6 @@ describe('expression', function() {
expect(evalExp('one<=two', scope)).to.equal(true); expect(evalExp('one<=two', scope)).to.equal(true);
expect(evalExp('x contains "x"', scope)).to.equal(false); expect(evalExp('x contains "x"', scope)).to.equal(false);
expect(evalExp('x contains "X"', scope)).to.equal(true); expect(evalExp('x contains "X"', scope)).to.equal(true);
expect(evalExp('x contains z', scope)).to.equal(false);
expect(evalExp('"<=" == "<="', scope)).to.equal(true); expect(evalExp('"<=" == "<="', scope)).to.equal(true);
}); });
@@ -51,7 +49,7 @@ describe('expression', function() {
}); });
it("should eval range expression", function() { it("should eval range expression", function() {
expect(evalExp('(2..4)', scope)).to.deep.equal([2,3,4]); expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4]);
expect(evalExp('(two..4)', scope)).to.deep.equal([2,3,4]); expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4]);
}); });
}); });