-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathhandlebars-helpers.ts
More file actions
98 lines (92 loc) · 2.29 KB
/
handlebars-helpers.ts
File metadata and controls
98 lines (92 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Handlebar helper functions.
*
* Helpers should be registered in app.module.ts
*/
import { mapJobClassV4toV3 } from "src/jobs/job-v3-mappings";
/**
* Convert json objects to HTML
*
* Supports:
* - boolean, numbers, and strings without modification
* - Arrays as <ul>
* - Objects as key: value pairs separated by <br/>
* - null as "Not specified"
* @param json
* @returns
*/
export const unwrapJSON = (json: unknown): string | number => {
if (json === null) {
return "Not specified";
}
if (typeof json === "boolean") {
return json ? "Yes" : "No";
}
if (typeof json === "number" || typeof json === "string") {
return json;
}
if (Array.isArray(json)) {
return (
"<ul style='padding-left: 1em'>" +
json
.map(
(elem) =>
"<li style='margin-bottom: 1em'>" + unwrapJSON(elem) + "</li>",
)
.join("") +
"</ul>"
);
}
if (typeof json === "object") {
return Object.keys(json as Record<string, unknown>)
.map((key) => {
return (
formatCamelCase(key) +
": " +
unwrapJSON(json[key as keyof typeof json])
);
})
.join("<br/>");
}
return "Not specified";
};
export const formatCamelCase = (camelCase: string): string => {
const match = camelCase.replace(/([A-Z])/g, " $1");
const words = match.charAt(0).toUpperCase() + match.slice(1);
return words;
};
/**
* Convert a handlebars context to a json string
*
* Useful for debugging, eg "{{{jsonify this}}}". Results contain newlines.
* @param context Handlebars variable
* @returns string
*/
export const jsonify = (context: unknown): string => {
return JSON.stringify(context, null, 3);
};
/**
* URL encode input
* @param context Handlebars variable
* @returns URL-encoded string
*/
export const urlencode = (context: string): string => {
return encodeURIComponent(context);
};
/**
* Base64 encode input
* @param context Handlebars variable
* @returns URL-encoded string
*/
export const base64enc = (context: string): string => {
return btoa(context);
};
export const handlebarsHelpers = {
unwrapJSON: unwrapJSON,
keyToWord: formatCamelCase,
eq: (a: unknown, b: unknown) => a === b,
jsonify: jsonify,
job_v3: mapJobClassV4toV3,
urlencode: urlencode,
base64enc: base64enc,
};