Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions plugins/empty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { SafeString } from "../core/environment.ts";
import type { Environment, Plugin } from "../core/environment.ts";

export default function (): Plugin {
return (env: Environment) => {
env.filters.empty = (value: unknown): boolean => {
if (!value) return true;
if (typeof value == "string" || value instanceof SafeString) {
return value.toString().trim() == "";
}
if (typeof value != "object") return false;
if (Array.isArray(value)) return value.length == 0;
return false;
};
};
}
2 changes: 2 additions & 0 deletions plugins/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import echoTag from "./echo.ts";
import escape from "./escape.ts";
import unescape from "./unescape.ts";
import trim from "./trim.ts";
import empty from "./empty.ts";

export default function (): Plugin {
return (env: Environment) => {
Expand All @@ -31,5 +32,6 @@ export default function (): Plugin {
env.use(escape());
env.use(unescape());
env.use(trim());
env.use(empty());
};
}
73 changes: 73 additions & 0 deletions test/empty.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { test } from "./utils.ts";

Deno.test("Escape filter", async () => {
await test({
template: `
NaN: {{ NaN |> empty }}
`,
expected: "NaN: true",
});

await test({
template: `
Zero: {{ 0 |> empty }}
`,
expected: "Zero: true",
});

await test({
template: `
One: {{ 1 |> empty }}
`,
expected: "One: false",
});

await test({
template: `
Null: {{ null |> empty }}
`,
expected: "Null: true",
});

await test({
template: `
Empty object: {{ {} |> empty }}
`,
expected: "Empty object: false",
});

await test({
template: `
Empty array: {{ [] |> empty }}
`,
expected: "Empty array: true",
});

await test({
template: `
Array with empty slot: {{ Array(1) |> empty }}
`,
expected: "Array with empty slot: false",
});

await test({
template: `
Empty string: {{ "" |> empty }}
`,
expected: "Empty string: true",
});

await test({
template: String.raw`
Whitespace only: {{ " \n\t " |> empty }}
`,
expected: "Whitespace only: true",
});

await test({
template: `
String of zero: {{ "0" |> empty }}
`,
expected: "String of zero: false",
});
});