Skip to content

quadrant-newmedia/auto_escape

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

auto_escape

A BASIC type script utility for building html using tagged template literals, where all expressions are automatically escaped.

All it does is help you generate html while avoiding XSS vulnerabilities. Intended to replace templating libraries (eg. moustache.js).

Compared to templating, you have: PRO: minimal overhead, easy to read PRO: type script will check your types; no render-time errors CON: your html lives inside template strings literals in js files, so you don't get syntax highlighting

Useful when you don't want to set up a full "component framework" (eg. react, vue, lit, etc.).

Explanation by example

import {auto_escape, TrustedHTML} from '@qnc/autoescape';

// Static parts aren't escaped
console.assert(auto_escape`<i></i>`.html == "<i></i>");

// You can insert regular characters
console.assert(auto_escape`<i>${"apple"}</i>`.html == "<i>apple</i>");

// You can insert numbers
console.assert(auto_escape`<i>${1}</i>`.html == "<i>1</i>");

// You can insert arrays
console.assert(auto_escape`<i>${[1, 2, 3]}</i>`.html == "<i>123</i>");

// Special characters are escaped
console.assert(
    auto_escape`<i>${"<>\"'&"}</i>`.html == "<i>&lt;&gt;&quot;&#039;&amp;</i>",
);

// it's composable
const inner = auto_escape`<i>${3}</i>`;
console.assert(auto_escape`<b>${inner}</b>`.html == "<b><i>3</i></b>");

// You can use TrustedHTML to trust other sources of HTML
console.assert(
    auto_escape`<i>${new TrustedHTML("<i></i>")}</i>`.html == "<i><i></i></i>",
);

// You can put expressions in attributes
console.assert(
    auto_escape`<a href="mailto:${'"John Doe" <john@example.com>'}">email John Doe</a>`
        .html ==
        '<a href="mailto:&quot;John Doe&quot; &lt;john@example.com&gt;">email John Doe</a>',
);

// Slightly more complex case
const users = [
    { first_name: "Alex", last_name: "Fischer" },
    { first_name: "John", last_name: "Doe" },
    { first_name: "Jane", last_name: "Doe" },
];
console.assert(
    auto_escape`
        <ul>
            ${users.map((u) => auto_escape`<li>${u.first_name} ${u.last_name}</li>`)}
        </ul>
    `.html ==
        `
        <ul>
            <li>Alex Fischer</li><li>John Doe</li><li>Jane Doe</li>
        </ul>
    `,
);

About

Typescript HTML generation with tagged template literals, minus the XSS

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors