From 80bc17686bbf41be010a9f87a3a118c37362f833 Mon Sep 17 00:00:00 2001 From: talsabagport Date: Mon, 25 Dec 2023 12:51:33 +0200 Subject: [PATCH] fix cr comment and bug + add test --- lib/template.js | 6 +++--- test/template.test.js | 11 +++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/template.js b/lib/template.js index d5aaf4e..04219c5 100644 --- a/lib/template.js +++ b/lib/template.js @@ -58,8 +58,8 @@ const render = (inputJson, template) => { } const firstIndex = indices[0]; - if (template.trim().startsWith('{{') && template.trim().endsWith('}}')) { - // If entire string is a template, evaluate and return + if (indices.length === 1 && template.trim().startsWith('{{') && template.trim().endsWith('}}')) { + // If entire string is a template, evaluate and return the result with the original type return jq.exec(inputJson, template.slice(firstIndex.start, firstIndex.end)); } @@ -67,7 +67,7 @@ const render = (inputJson, template) => { indices.forEach((index, i) => { const jqResult = jq.exec(inputJson, template.slice(index.start, index.end)); result += - // Add to the result the evaluated jq of the current template + // Add to the result the stringified evaluated jq of the current template (typeof jqResult === 'string' ? jqResult : JSON.stringify(jqResult)) + // Add to the result from template end index. if last template index - until the end of string, else until next start index template.slice( diff --git a/test/template.test.js b/test/template.test.js index 04a4068..1817557 100644 --- a/test/template.test.js +++ b/test/template.test.js @@ -125,5 +125,16 @@ describe('template', () => { expect(render({'{{""}}': 'bar'})).toEqual({}); expect(render({'{{\'\'}}': 'bar'})).toEqual({}); }); + it('recursive templates should work', () => { + const json = { foo: 'bar', bar: 'foo' }; + const render = (input) => jq.renderRecursively(json, input); + + expect(render({'{{.foo}}': '{{.bar}}{{.foo}}'})).toEqual({bar: 'foobar'}); + expect(render({'{{.foo}}': {foo: '{{.foo}}'}})).toEqual({bar: {foo: 'bar'}}); + expect(render([1, true, null, undefined, '{{.foo}}', 'https://{{.bar}}.com'])).toEqual([1, true, null, undefined, 'bar', 'https://foo.com']); + expect(render([['{{.bar}}{{.foo}}'], 1, '{{.bar | ascii_upcase}}'])).toEqual([['foobar'], 1, 'FOO']); + expect(render([{'{{.bar}}': [false, '/foo/{{.foo + .bar}}']}])).toEqual([{foo: [false, '/foo/barfoo']}]); + expect(render({foo: [{bar: '{{1}}'}, '{{empty}}']})).toEqual({foo: [{bar: 1}, undefined]}); + }); })