Skip to content

Commit

Permalink
Merge pull request gastonrobledo#12 from pocketken/fix-lookup-property
Browse files Browse the repository at this point in the history
fix gastonrobledo#11: support nested async values in context
  • Loading branch information
gastonrobledo authored Jan 14, 2023
2 parents 3cac36a + ce53d18 commit 99186d0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,20 @@ function asyncHelpers(hbs) {
return _escapeExpression(value)
}

function lookupProperty(containerLookupProperty) {
return function(parent, propertyName) {
if (isPromise(parent)) {
return parent.then((p) => containerLookupProperty(p, propertyName))
}
return containerLookupProperty(parent, propertyName)
}
}

handlebars.template = function(spec) {
spec.main_d = (prog, props, container, depth, data, blockParams, depths) => async(context) => {
// const main = await spec.main
container.escapeExpression = escapeExpression
container.lookupProperty = lookupProperty(container.lookupProperty)
const v = spec.main(container, context, container.helpers, container.partials, data, blockParams, depths)
return v
}
Expand Down
26 changes: 26 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,32 @@ describe('Test async helpers', () => {

})

it('Test lookupProperty', async() => {
const hbs = asyncHelpers(Handlebars),
template = `{{person.[0].firstName}}`,
expected = 'John'
const compiled = hbs.compile(template),
result = await compiled({
person: [
Promise.resolve({firstName: 'John', lastName: 'Q'}),
]
})
should.equal(result, expected)
})

it('Test lookupProperty with nested promises', async() => {
const hbs = asyncHelpers(Handlebars),
template = `{{person.[0].firstName}}`,
expected = 'John'
const compiled = hbs.compile(template),
result = await compiled({
person: Promise.all([
Promise.resolve({firstName: 'John', lastName: 'Q'}),
])
})
should.equal(result, expected)
})

it('Test with helper', async () => {
const hbs = asyncHelpers(Handlebars),
template = `<div class="names">
Expand Down

0 comments on commit 99186d0

Please sign in to comment.