Skip to content

Instantly share code, notes, and snippets.

@jdanyow
Created April 19, 2021 23:33
Show Gist options
  • Save jdanyow/ee76954313ac6919422379036196d5ac to your computer and use it in GitHub Desktop.
Save jdanyow/ee76954313ac6919422379036196d5ac to your computer and use it in GitHub Desktop.
import escape_html from 'escape-html';
export class TemplateResult {
constructor(
public readonly strings: TemplateStringsArray,
public readonly values: any[]
) {}
}
export function html(strings: TemplateStringsArray, ...values: any[]) {
return new TemplateResult(strings, values);
}
export function render(value: any) {
let result = '';
if (value === null || value === undefined || value === '') {
// do nothing.
} else if (Array.isArray(value)) {
for (const item of value) {
result += render(item);
}
} else if (value instanceof TemplateResult) {
const { strings, values } = value;
result += strings[0];
for (let i = 1; i < strings.length; i++) {
const value = values[i - 1];
result += render(value);
result += strings[i];
}
} else if (value instanceof UnsafeHTML) {
result += value.value;
} else {
result += escape_html(typeof value === 'string' ? value : String(value));
}
return result;
}
class UnsafeHTML {
public readonly value: string;
constructor(value: string) {
this.value = typeof value === 'string' ? value : String(value);
}
public toString() {
return this.value;
}
}
export function unsafeHTML(value: string) {
return new UnsafeHTML(value);
}
export function attr(name: string, value: string | undefined | null) {
return value === null || value === undefined || value === ''
? ''
: new UnsafeHTML(`${escape_html(name)}="${escape_html(value)}"`);
}
export function booleanAttr(name: string, value: any) {
return Boolean(value) ? new UnsafeHTML(escape_html(name)) : '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment