Skip to content

Commit 3eeec4b

Browse files
committed
Fix a problem with indentation
1 parent 0b7ba05 commit 3eeec4b

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

Diff for: index.js

+38-1
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,45 @@ function asyncHelpers(hbs) {
7979

8080
return function(context, execOptions) {
8181
context = context || {}
82+
let indent = false;
83+
if (execOptions?.indent) {
84+
execOptions.indent = undefined
85+
indent = true
86+
}
87+
const result = compiled.call(handlebars, context, execOptions)
88+
if (!indent) {
89+
return result
90+
} else {
91+
92+
93+
// this are dummy methods to work with handlebar code, it is only designed for usage with that, otherwise it may break!
94+
result.split = () => { return result }
95+
result.join = () => { return result }
96+
result.length = 0
97+
98+
// this is a proxy to post process the promise result, it overrides the then method and therefore does the indent split - join job after the result is here!
99+
const resultProxy = new Proxy(result, {
100+
then(cb) {
101+
result.then(res => {
102+
if (indent) {
103+
const lines = res.split('\n');
104+
for (let i = 0, l = lines.length; i < l; i++) {
105+
if (!lines[i] && i + 1 === l) {
106+
break;
107+
}
108+
109+
lines[i] = indent + lines[i];
110+
}
111+
res = lines.join('\n');
112+
}
113+
return cb(res)
114+
})
115+
}
116+
})
82117

83-
return compiled.call(handlebars, context, execOptions)
118+
return resultProxy
119+
120+
}
84121
}
85122
}
86123
handlebars.ASYNC_VERSION = app.version

Diff for: test/test.js

+19
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,25 @@ describe('Test async helpers', () => {
320320
should.equal(result, expected)
321321
})
322322

323+
it('Test indentation with async partial', async () => {
324+
const hbs = asyncHelpers(Handlebars),
325+
template = '<div>Parent {{> child}}</div>',
326+
child = '<div>Child:\n\t\t\t{{> grandChild}}</div>',
327+
grandChild = '<p>\nGrand Child: {{#delayed 50}}{{/delayed}}\n</p>',
328+
expected = '<div>Parent <div>Child:\n\t\t\t<p>\nGrand Child: Hello!\n</p></div></div>'
329+
hbs.registerHelper('delayed', (time) => {
330+
return new Promise((resolve) => {
331+
setTimeout(() => resolve('Hello!'), time)
332+
})
333+
})
334+
hbs.registerPartial('child', child)
335+
hbs.registerPartial('grandChild', grandChild)
336+
const compiled = hbs.compile(template),
337+
result = await compiled()
338+
should.equal(result, expected)
339+
340+
})
341+
323342
it('Test synchronous helper', async () => {
324343
const hbs = asyncHelpers(Handlebars),
325344
template = '<div>Value: {{#multiply 100 20}}{{/multiply}}</div>',

0 commit comments

Comments
 (0)