What
Domm is a small library to create safe HTML and DOM nodes using ES6 template literals.
Why
It's lightweight and relies on native JS functionality. For anything non-trivial, this doesn't compete with a real template language like pug, or a library like react.
Installation
npm install --save domm
Usage
Basic
const D = ; Dhtml`<h1>Hello World!</h1>`;// => '<h1>Hello World!</h1>' Ddom`<h1>Hello World!</h1>`;// => new instance of <HTMLHeadingElement> Ddom` <a href="/">Home</a> <a href="/about">About</a>`;// => new instance of <NodeList> containing 2 links
Variable interpolation
// Stringconst headingText = 'Houses'; // Objectconst headingAttrs = class: 'heading-main' ; // Arrayconst names = 'Lannister' 'Stark' 'Tyrell'; // Elementconst backLink = document; Dhtml` <div> <h1 ></h1> <ul> </ul> </div>`;// =>// <div>// <h1 class="heading-main">Houses</h1>// <ul>// <li>Lannister</li><li>Stark</li><li>Tyrell</li>// </ul>// <a class="js-link-back" href="/">Back to home</a>// </div>
Note that the list of names required D.html
to be used on the inner template literal. Without this, the HTML in the list would have been escaped:
"<li>Lannister</li><li>Stark</li><li>Tyrell</li>"
All strings that are interpolated are escaped in this way. To dangerously escape a variable that is not defined via a template literal, use the D
constructor:
const title = ; Ddom`<h1></h1>`;