Add collect filter to template renderer.

This filter can collect attributes from items having the
same key into a single item.

Can be used in templates like this:

{% for Entry in Sequence.Entries |
   collect("ShotPointId", ["EntryType", "Comment"]) %}

to avoid duplicating shotpoint numbers.
This commit is contained in:
D. Berge
2021-05-15 20:07:02 +02:00
parent e57c362d94
commit ef798860cd

View File

@@ -13,6 +13,22 @@ function njkFind (ary, key, value) {
}
}
function njkCollect (entries, key, collectables) {
const out = [];
for (const entry of entries) {
if (out.find(i => i[key] == entry[key])) {
continue;
}
const others = entries.filter(item => item[key] == entry[key]);
const obj = Object.assign({}, entry);
for (const collectable of collectables) {
obj[collectable] = others.map(i => i[collectable]).filter(i => typeof i !== "undefined" && i !== "");
}
out.push(obj);
}
return out;
}
function njkPadStart (str, len, chr) {
return String(str).padStart(len, chr);
}
@@ -42,6 +58,7 @@ async function render (data, template) {
const nenv = nunjucks.configure(Path.dirname(template), {autoescape: false, lstripBlocks: false, trimBlocks: false});
nenv.addFilter('find', njkFind);
nenv.addFilter('collect', njkCollect);
nenv.addFilter('padStart', njkPadStart);
nenv.addFilter('timestamp', njkTimestamp);
nenv.addFilter('markdown', njkMarkdown);