From e37824fd8a71a1f2c529eaafb7bb308e91787fa8 Mon Sep 17 00:00:00 2001 From: harttle Date: Fri, 12 Feb 2021 13:38:18 +0800 Subject: [PATCH] feat: support function calls, closes #222 --- src/context/context.ts | 2 +- test/e2e/issues.ts | 8 ++++++++ test/integration/builtin/filters/html.ts | 3 --- test/unit/context/context.ts | 8 ++++++++ 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/context/context.ts b/src/context/context.ts index c12c0269a..caba5c7e0 100644 --- a/src/context/context.ts +++ b/src/context/context.ts @@ -70,8 +70,8 @@ export class Context { export function readProperty (obj: Scope, key: string) { if (isNil(obj)) return obj obj = toLiquid(obj) + if (isFunction(obj[key])) return obj[key]() if (obj instanceof Drop) { - if (isFunction(obj[key])) return obj[key]() if (obj.hasOwnProperty(key)) return obj[key] return obj.liquidMethodMissing(key) } diff --git a/test/e2e/issues.ts b/test/e2e/issues.ts index 7b418043a..fddccbeff 100644 --- a/test/e2e/issues.ts +++ b/test/e2e/issues.ts @@ -70,4 +70,12 @@ describe('Issues', function () { const html = await engine.parseAndRender(`{{ '{{' }}{{ '}}' }}`) expect(html).to.equal('{{}}') }) + it('#222 Support function calls', async () => { + const engine = new Liquid() + const html = await engine.parseAndRender( + `{{ obj.property }}`, + { obj: { property: () => 'BAR' } } + ) + expect(html).to.equal('BAR') + }) }) diff --git a/test/integration/builtin/filters/html.ts b/test/integration/builtin/filters/html.ts index fc0e605ff..0d5442c35 100644 --- a/test/integration/builtin/filters/html.ts +++ b/test/integration/builtin/filters/html.ts @@ -9,9 +9,6 @@ describe('filters/html', function () { it('should escape normal string', function () { return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara') }) - it('should escape function', function () { - return test('{{ func | escape }}', { func: function () {} }, 'function () { }') - }) it('should escape undefined', function () { return test('{{ nonExistent.value | escape }}', '') }) diff --git a/test/unit/context/context.ts b/test/unit/context/context.ts index fb95deb8d..432859150 100644 --- a/test/unit/context/context.ts +++ b/test/unit/context/context.ts @@ -15,6 +15,8 @@ describe('Context', function () { first: 'f', last: 'l' }, + func: () => 'FUNC', + objFunc: () => ({ prop: 'PROP' }), bar: { zoo: 'coo', 'Mr.Smith': 'John', @@ -59,6 +61,12 @@ describe('Context', function () { it('should read .last of array', async function () { expect(ctx.get(['bar', 'arr', 'last'])).to.equal('b') }) + it('should call function', async function () { + expect(ctx.get(['func'])).to.equal('FUNC') + }) + it('should call function before read nested property', async function () { + expect(ctx.get(['objFunc', 'prop'])).to.equal('PROP') + }) }) describe('#getFromScope()', function () {