From b307f6ffd0923245ef9de5bd135f7f2b67b49a5d Mon Sep 17 00:00:00 2001 From: chenos Date: Mon, 20 Mar 2017 15:06:32 +0800 Subject: [PATCH] Size can also be used with dot notation (#25) * Size can also be used with dot notation (for example, {{ my_string.size }}). * Fixed test failed. * Optimization --- src/scope.js | 10 ++++++++++ test/filters.js | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/src/scope.js b/src/scope.js index cf1a404c1..3edea618e 100644 --- a/src/scope.js +++ b/src/scope.js @@ -1,6 +1,7 @@ const _ = require('./util/underscore.js'); const lexical = require('./lexical.js'); const assert = require('./util/assert.js'); +const toStr = Object.prototype.toString; var Scope = { getAll: function() { @@ -75,7 +76,16 @@ var Scope = { throw new TypeError('undefined variable'); } var variable = obj[varName]; + var lastName = paths.pop(); paths.forEach(p => variable = variable[p]); + if (undefined !== lastName) { + if (lastName === 'size' && + (toStr.call(variable) === '[object Array]' + || toStr.call(variable) === '[object String]')) { + return variable.length; + } + variable = variable[lastName] + } return variable; }, diff --git a/test/filters.js b/test/filters.js index 06b25a3f5..87d577949 100644 --- a/test/filters.js +++ b/test/filters.js @@ -221,6 +221,10 @@ describe('filters', function() { ' | split: ", " %}{{ my_array | size }}', '4'); }); + it('should also be used with dot notation - string', + () => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28')); + it('should also be used with dot notation - array', + () => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4')); }); describe('slice', function() {