diff --git a/packages/environment/src/filters.ts b/packages/environment/src/filters.ts index d228407..6368ce9 100644 --- a/packages/environment/src/filters.ts +++ b/packages/environment/src/filters.ts @@ -1478,7 +1478,10 @@ export const rejectattr: SelectReject = nunjucksFunction(["value"], { } else throw new Error("unreachable"); }); -export function tojson(o: unknown, indent = 0): string { +export const tojson = nunjucksFunction(["o", "indent"])(function tojson( + o: unknown, + indent: number = 0, +): string { if (o === undefined) { return "undefined"; } @@ -1495,7 +1498,7 @@ export function tojson(o: unknown, indent = 0): string { .replace(/&/g, "\\u0026") .replace(/'/g, "\\u0027"), ); -} +}); export default { abs, diff --git a/test/filters.test.ts b/test/filters.test.ts index c2d3712..eda7743 100644 --- a/test/filters.test.ts +++ b/test/filters.test.ts @@ -993,7 +993,12 @@ describe("filters", () => { }); it("indent: 2", () => { - const tmpl = env.fromString("{{ x | tojson(2) }}"); + let tmpl = env.fromString("{{ x | tojson(2) }}"); + expect(tmpl.render({ x: { foo: "bar" } })).toBe('{\n "foo": "bar"\n}'); + expect(tmpl.render({ x: ["foo", "bar"] })).toBe( + '[\n "foo",\n "bar"\n]', + ); + tmpl = env.fromString("{{ x | tojson(indent=2) }}"); expect(tmpl.render({ x: { foo: "bar" } })).toBe('{\n "foo": "bar"\n}'); expect(tmpl.render({ x: ["foo", "bar"] })).toBe( '[\n "foo",\n "bar"\n]',