feat: support function calls, closes #222

This commit is contained in:
harttle
2021-02-12 13:47:30 +08:00
parent 81e11bb9c4
commit e37824fd8a
4 changed files with 17 additions and 4 deletions
+1 -1
View File
@@ -70,8 +70,8 @@ export class Context {
export function readProperty (obj: Scope, key: string) { export function readProperty (obj: Scope, key: string) {
if (isNil(obj)) return obj if (isNil(obj)) return obj
obj = toLiquid(obj) obj = toLiquid(obj)
if (isFunction(obj[key])) return obj[key]()
if (obj instanceof Drop) { if (obj instanceof Drop) {
if (isFunction(obj[key])) return obj[key]()
if (obj.hasOwnProperty(key)) return obj[key] if (obj.hasOwnProperty(key)) return obj[key]
return obj.liquidMethodMissing(key) return obj.liquidMethodMissing(key)
} }
+8
View File
@@ -70,4 +70,12 @@ describe('Issues', function () {
const html = await engine.parseAndRender(`{{ '{{' }}{{ '}}' }}`) const html = await engine.parseAndRender(`{{ '{{' }}{{ '}}' }}`)
expect(html).to.equal('{{}}') 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')
})
}) })
-3
View File
@@ -9,9 +9,6 @@ describe('filters/html', function () {
it('should escape normal string', function () { it('should escape normal string', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara') return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
}) })
it('should escape function', function () {
return test('{{ func | escape }}', { func: function () {} }, 'function () { }')
})
it('should escape undefined', function () { it('should escape undefined', function () {
return test('{{ nonExistent.value | escape }}', '') return test('{{ nonExistent.value | escape }}', '')
}) })
+8
View File
@@ -15,6 +15,8 @@ describe('Context', function () {
first: 'f', first: 'f',
last: 'l' last: 'l'
}, },
func: () => 'FUNC',
objFunc: () => ({ prop: 'PROP' }),
bar: { bar: {
zoo: 'coo', zoo: 'coo',
'Mr.Smith': 'John', 'Mr.Smith': 'John',
@@ -59,6 +61,12 @@ describe('Context', function () {
it('should read .last of array', async function () { it('should read .last of array', async function () {
expect(ctx.get(['bar', 'arr', 'last'])).to.equal('b') 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 () { describe('#getFromScope()', function () {