@so1ve/html
Videos
Demonstration
Code Review
Installation
$ npm install @so1ve/html
Use @so1ve/html with Prettier (automatic formatting), and the Visual Studio Code extensions Prettier - Code formatter (Prettier support) and es6-string-html (syntax highlighting).
Features, Usage, and Examples
-
Use tagged template literals as an HTML template engine. For example:
import html from "@so1ve/html";
console.log(html`<p>${"Leandro Facchinetti"}</p>`);
-
Safe by default. For example:
console.log(html`<p>${`<script>alert(1);</script>`}</p>`);
-
Unsafely interpolate trusted HTML with $${...}
. For example:
console.log(html`<p>$${`<span>Leandro Facchinetti</span>`}</p>`);
-
Join interpolated arrays. For example:
console.log(html`<p>${["Leandro", " ", "Facchinetti"]}</p>`);
Array interpolations are safe by default; if you wish to unsafely interpolate an array of trusted HTML use $${[...]}
.
-
@so1ve/html doesn’t encode HTML itself. It relies on he, which is much more robust than any bespoke encoding.
-
@so1ve/html doesn’t try to format the output. If you need pretty HTML, you may call Prettier programmatically on the output.
-
@so1ve/html generates strings. No kind of virtual DOM here. For readability, the HTML
type is exported in TypeScript, and you may use it like in the following example:
import { html, HTML } from ".";
const name: HTML = html`<p>Leandro Facchinetti</p>`;
console.log(name);
-
@so1ve/html sanitizes (removes) invalid XML characters. It uses sanitize-xml-string. For example:
console.log(html`<p>A backspace is invalid in XML: |\b|</p>`);
Related Projects
Prior Art