Public
Script
Readme

Render html by tagged templates

You can use this simple function to compose components, and you can also format the content within html`` elegantly in VSCode.

Example

const TitleTextDefault = ':)' const Title = (text)=> html`<h1>${text || TitleTextDefault}</h1>` // -> "<html><body><h1>:)</h1></body></html>" html`<html><body>${Title}</body></html>` // -> "<html><body><h1>!</h1></body></html>" html`<html><body>${Title('!')}</body></html>`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getValue(value: unknown) {
if (value instanceof Function) {
return getValue(value());
}
if (typeof value === "object") {
return JSON.stringify(value);
}
return value;
}
export function html(strings: TemplateStringsArray, ...values: unknown[]) {
const len = strings.length;
return strings.reduce((renderStr, str, idx) => {
const value = idx >= len - 1 ? "" : getValue(values[idx]);
return renderStr + str + value;
}, "");
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
November 19, 2023