Last active
September 13, 2016 08:56
-
-
Save sielay/8c80fe88c8911db833b2959af00e3c8e to your computer and use it in GitHub Desktop.
Dust helper for recurrent templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Dust doesn't really like recurrent templates for various reasons (vars visibility etc). To resolve that issue you can use following helper | |
*/ | |
engine.helpers.has = function (chunk, context, bodies, params) { | |
let tested = params.key; | |
if (tested[params.field] === undefined || tested[params.field] === null || tested[params.field].length === 0) { | |
return chunk; | |
} | |
return chunk.render(bodies.block, context); | |
}; | |
engine.helpers.recurrent = function (chunk, context, bodies, params) { | |
let | |
partial = params.partial, | |
collection = params.collection, | |
path = params.path, | |
other = {}; | |
Object | |
.keys(params) | |
.forEach(paramName => { | |
if (['partial', 'collection', 'path'].indexOf(params) === -1) { | |
other[paramName] = params[paramName]; | |
} | |
}); | |
if (!collection || !collection.length) { | |
return chunk.end(); | |
} | |
return chunk.map(inner => { | |
let head = Promise.resolve(); | |
collection.forEach((item, idx) => { | |
let copy = _.merge({}, item, other, { | |
$idx: idx, | |
path: (path ? (path + '.') : '') + idx, | |
parent: path || '' | |
}); | |
head = head | |
.then(() => { | |
let lock = false; | |
return new Promise((resolve, reject) => engine.render(partial, copy, (error, out) => { | |
if (lock) { // for some reason callback is called few times | |
return resolve(); | |
} | |
lock = true; | |
if (error) { | |
return reject(error); | |
} | |
inner.write(out); | |
resolve(); | |
})); | |
}); | |
}); | |
head | |
.then(() => { | |
inner.end(); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had to update to guarantee order.