Skip to content

Instantly share code, notes, and snippets.

@sielay
Last active September 13, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sielay/8c80fe88c8911db833b2959af00e3c8e to your computer and use it in GitHub Desktop.
Save sielay/8c80fe88c8911db833b2959af00e3c8e to your computer and use it in GitHub Desktop.
Dust helper for recurrent templates
/*
* 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();
});
});
};
@sielay
Copy link
Author

sielay commented Sep 13, 2016

Had to update to guarantee order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment