From 6d0e232c9743177e6739ed6dd4f49a2719bce673 Mon Sep 17 00:00:00 2001 From: Josemi Juanes <5751201+jmjuanes@users.noreply.github.com> Date: Mon, 8 Apr 2024 18:44:13 +0200 Subject: [PATCH] fix: considering empty arrays as falsy values (#5) --- index.js | 4 ++-- test.js | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 9b115f6..b13ae8c 100644 --- a/index.js +++ b/index.js @@ -30,8 +30,8 @@ const compile = (tokens, output, ctx, opt, index, section) => { const negate = tokens[i].startsWith("^"); if (!negate && value && Array.isArray(value)) { const j = i + 1; - value.forEach(item => { - i = compile(tokens, output, item, opt, j, t); + (value.length > 0 ? value : [""]).forEach(item => { + i = compile(tokens, value.length > 0 ? output : [], item, opt, j, t); }); } else { diff --git a/test.js b/test.js index b37da0a..007a4d3 100644 --- a/test.js +++ b/test.js @@ -67,6 +67,13 @@ describe("{{# xyz }}", () => { assert.equal(m("{{#items}}{{name}}-{{/items}}", data), "Susan-Bob-"); }); + it("should not iterate over an empty array", () => { + const data = { + items: [], + }; + assert.equal(m("List of items: {{#items}}{{.}},{{/items}}", data), "List of items: "); + }); + it("should throw an error for unmatched end of section", () => { const data = {name: "Bob"}; try {