very-basic-html-templates
v0.1.1
Published
A tiny tagged template literal library for safe HTML generation
Readme
very-basic-html-templates
A tiny tagged template literal library for safe HTML generation. Interpolated values are automatically escaped; values explicitly marked as safe or unsafe pass through as-is.
Clone
# SSH (read-write, requires key)
git clone [email protected]:repos/very-basic-html-templates.git
# git:// (read-only, public)
git clone git://git.spooky.click/very-basic-html-templates.gitInstall
npm install very-basic-html-templatesUsage
import { html, unsafeHTML, renderToString } from "very-basic-html-templates";
const userName = '<script>alert("xss")</script>';
const page = html`<div class="greeting">Hello, ${userName}!</div>`;
console.log(renderToString(page));
// <div class="greeting">Hello, <script>alert("xss")</script>!</div>Composing templates
html returns a SafeHTML instance. When interpolated into another html tag, it is not double-escaped:
const header = html`<h1>${title}</h1>`;
const page = html`<body>${header}<main>${content}</main></body>`;Opting out of escaping
If you have a string you trust and want to interpolate without escaping, wrap it with unsafeHTML:
const richText = unsafeHTML(sanitizedHtmlFromDatabase);
const page = html`<article>${richText}</article>`;API
| Export | Description |
|---|---|
| html | Tagged template literal. Escapes interpolated values, returns SafeHTML. |
| renderToString(safe) | Unwraps a SafeHTML to a plain string. |
| unsafeHTML(s) | Wraps a string as UnsafeHTML so it won't be escaped when interpolated. |
| escapeHtml(s) | Escapes & < > " ' in a string. |
| SafeHTML | Class representing escaped/trusted HTML. |
| UnsafeHTML | Class representing raw HTML that should not be escaped. |
License
BSD-3-Clause
