diff --git a/docs/usage/templates.md b/docs/usage/templates.md index 6bdf0688c235b4f28d148fd401dbe1488f46d009..470c1d0efda945b7a99dc0a2cd944bd4aa204f0b 100644 --- a/docs/usage/templates.md +++ b/docs/usage/templates.md @@ -20,3 +20,13 @@ Some are configuration options passed through, while others are generated as par ## Other available fields <!-- Insert runtime fields here --> + +## Additional Handlebars helpers + +### stringToPrettyJSON + +If you want to print pretty JSON with Handlebars you can use the built-in function `stringToPrettyJSON` like this: + +`{{{stringToPrettyJSON myvar}}}` + +In the example above `myvar` is a variable/field, that contains valid JSON. diff --git a/lib/util/template/__snapshots__/index.spec.ts.snap b/lib/util/template/__snapshots__/index.spec.ts.snap index e9fc7048944be908cb8b100e8c0e8b2cce380ec3..d900a0a75152385265af6a7e5bc794a54ea883e5 100644 --- a/lib/util/template/__snapshots__/index.spec.ts.snap +++ b/lib/util/template/__snapshots__/index.spec.ts.snap @@ -1,3 +1,11 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`util/template/index filters out disallowed fields 1`] = `"github token = \\"\\""`; + +exports[`util/template/index string to pretty JSON 1`] = ` +"{ + \\"some\\": { + \\"fancy\\": \\"json\\" + } +}" +`; diff --git a/lib/util/template/index.spec.ts b/lib/util/template/index.spec.ts index 652d0f5e35275779ced3151813c849304df66622..55ab3c7b27362cc2dda1a89221f1fb115066b2b1 100644 --- a/lib/util/template/index.spec.ts +++ b/lib/util/template/index.spec.ts @@ -18,4 +18,10 @@ describe('util/template/index', () => { expect(output).toContain('github'); expect(output).not.toContain('123test'); }); + it('string to pretty JSON ', () => { + const userTemplate = + '{{{ stringToPrettyJSON \'{"some":{"fancy":"json"}}\'}}}'; + const output = template.compile(userTemplate, undefined); + expect(output).toMatchSnapshot(); + }); }); diff --git a/lib/util/template/index.ts b/lib/util/template/index.ts index d5415734a1b11431203c7bdc6103357b9fec5409..4a4ad1ee33af6263d66cce68f33547c168da0ea1 100644 --- a/lib/util/template/index.ts +++ b/lib/util/template/index.ts @@ -6,6 +6,10 @@ import { clone } from '../clone'; handlebars.registerHelper('encodeURIComponent', encodeURIComponent); +handlebars.registerHelper('stringToPrettyJSON', (input: string): string => + JSON.stringify(JSON.parse(input), null, 2) +); + // istanbul ignore next handlebars.registerHelper( 'replace',