@leafac/html

Radically Straightforward HTML

Usage no npm install needed!

<script type="module">
  import leafacHtml from 'https://cdn.skypack.dev/@leafac/html';
</script>

README

@leafac/html

HTML tagged template literals

Source Package Continuous Integration

Videos


Demonstration


Code Review

Installation

$ npm install @leafac/html

Use @leafac/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 "@leafac/html";
    
    console.log(html`<p>${"Leandro Facchinetti"}</p>`); // => <p>Leandro Facchinetti</p>
    
  • Safe by default. For example:

    console.log(html`<p>${`<script>alert(1);</script>`}</p>`); // => <p>&#x3C;script&#x3E;alert(1);&#x3C;/script&#x3E;</p>
    
  • Unsafely interpolate trusted HTML with ${...}. For example:

    console.log(html`<p>${`<span>Leandro Facchinetti</span>`}</p>`); // => <p><span>Leandro Facchinetti</span></p>
    
  • Join interpolated arrays. For example:

    console.log(html`<p>${["Leandro", " ", "Facchinetti"]}</p>`); // => <p>Leandro Facchinetti</p>
    

    Array interpolations are safe by default; if you wish to unsafely interpolate an array of trusted HTML use ${[...]}.

  • @leafac/html doesn’t encode HTML itself. It relies on he, which is much more robust than any bespoke encoding.

  • @leafac/html doesn’t try to format the output. If you need pretty HTML, you may call Prettier programmatically on the output.

  • @leafac/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);
    
  • @leafac/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>`); // => <p>A backspace is invalid in XML: ||</p>
    

Related Projects

Prior Art