Skip to content

Commit 99186d0

Browse files
Merge pull request gastonrobledo#12 from pocketken/fix-lookup-property
fix gastonrobledo#11: support nested async values in context
2 parents 3cac36a + ce53d18 commit 99186d0

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

index.js

+10
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,20 @@ function asyncHelpers(hbs) {
5252
return _escapeExpression(value)
5353
}
5454

55+
function lookupProperty(containerLookupProperty) {
56+
return function(parent, propertyName) {
57+
if (isPromise(parent)) {
58+
return parent.then((p) => containerLookupProperty(p, propertyName))
59+
}
60+
return containerLookupProperty(parent, propertyName)
61+
}
62+
}
63+
5564
handlebars.template = function(spec) {
5665
spec.main_d = (prog, props, container, depth, data, blockParams, depths) => async(context) => {
5766
// const main = await spec.main
5867
container.escapeExpression = escapeExpression
68+
container.lookupProperty = lookupProperty(container.lookupProperty)
5969
const v = spec.main(container, context, container.helpers, container.partials, data, blockParams, depths)
6070
return v
6171
}

test/test.js

+26
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,32 @@ describe('Test async helpers', () => {
7070

7171
})
7272

73+
it('Test lookupProperty', async() => {
74+
const hbs = asyncHelpers(Handlebars),
75+
template = `{{person.[0].firstName}}`,
76+
expected = 'John'
77+
const compiled = hbs.compile(template),
78+
result = await compiled({
79+
person: [
80+
Promise.resolve({firstName: 'John', lastName: 'Q'}),
81+
]
82+
})
83+
should.equal(result, expected)
84+
})
85+
86+
it('Test lookupProperty with nested promises', async() => {
87+
const hbs = asyncHelpers(Handlebars),
88+
template = `{{person.[0].firstName}}`,
89+
expected = 'John'
90+
const compiled = hbs.compile(template),
91+
result = await compiled({
92+
person: Promise.all([
93+
Promise.resolve({firstName: 'John', lastName: 'Q'}),
94+
])
95+
})
96+
should.equal(result, expected)
97+
})
98+
7399
it('Test with helper', async () => {
74100
const hbs = asyncHelpers(Handlebars),
75101
template = `<div class="names">

0 commit comments

Comments
 (0)