Skip to content

Commit

Permalink
fix(filter): wrap tojson with nunjucksFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
wenfw committed Sep 21, 2024
1 parent 3fe25e5 commit f2d3844
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
7 changes: 5 additions & 2 deletions packages/environment/src/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}
Expand All @@ -1495,7 +1498,7 @@ export function tojson(o: unknown, indent = 0): string {
.replace(/&/g, "\\u0026")
.replace(/'/g, "\\u0027"),
);
}
});

export default {
abs,
Expand Down
7 changes: 6 additions & 1 deletion test/filters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]',
Expand Down

0 comments on commit f2d3844

Please sign in to comment.