Open in a new tab

Parse an HTML template once, bind a data array to it and materialise the cards in the page; untrusted text stays inert, and user HTML goes through the sanitizer before it is inserted.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

You render lists and cards from data and want the three stages visible: parse (parser), bind (render), materialise (template). For most pages the uiSession wrapper does this for you (see fw/dom-ui-session); this example shows the pipeline underneath, and render.toHTML for a server or build-time string.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Give each template context a unique name (TPL.init(name, { to })).

What it shows

  • parser.fromHTML(html) once; #{name} placeholders bind text or attribute values, so a payload in the data is shown, never executed.
  • render.loop(template, dataArray) binds and rewrites ids without touching the DOM; template.elms(context, part.arr) inserts the result; template.clearAll(context) empties it.
  • render.toHTML(parseResult, data): the same template as an escaped string.
  • sanitize.sanitizeHtml(html) for HTML the user wrote: <b> stays, <script>, on* handlers and javascript: links go.

Code

main.js

javascriptApache-2.065 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { parser } from '@awacloud/fw/dom/rendering/parser.js';
import { render } from '@awacloud/fw/dom/rendering/render.js';
import { template } from '@awacloud/fw/dom/rendering/template.js';
import { sanitize } from '@awacloud/fw/dom/rendering/sanitize.js';

fw.runtime.registerAllDeep([parser, render, template, sanitize]);
const PARSER = fw.runtime.resolve('parser');
const RENDER = fw.runtime.resolve('render');
const TPL = fw.runtime.resolve('template');
const SANITIZE = fw.runtime.resolve('sanitize');

/** Stage 1: parse once. `#{name}` binds text or an attribute value, never markup. */
const CARD = PARSER.fromHTML('<article class="card"><h3>#{title}</h3><p>#{body}</p></article>');
const CONTEXT = 'dom-template';
TPL.init(CONTEXT, { to: '#cards', main: true });

/**
 * Stage 2 binds the data to a fresh copy of the template (no DOM touched);
 * stage 3 materialises the bound elements into the context.
 * @param {{ title: string, body: string }[]} cards
 * @returns {number} cards rendered
 */
export function renderCards(cards) {
    TPL.clearAll(CONTEXT);
    for (const part of RENDER.loop(CARD.template, cards)) TPL.elms(CONTEXT, part.arr);
    return cards.length;
}

/**
 * Stage 2 alone, to a string: what a server or a build step would emit.
 * @param {{ title: string, body: string }} card
 */
export const toHTML = (card) => RENDER.toHTML(CARD, card);

/**
 * User-supplied HTML keeps its allowed markup and loses scripts, event
 * handlers and javascript: URLs.
 * @param {string} html
 */
export const cleanHTML = (html) => SANITIZE.sanitizeHtml(html);

const body = /** @type {HTMLTextAreaElement} */ (document.getElementById('body'));
const comment = /** @type {HTMLTextAreaElement} */ (document.getElementById('comment'));
const rich = /** @type {HTMLElement} */ (document.getElementById('rich'));
const ssr = /** @type {HTMLElement} */ (document.getElementById('ssr'));

function updateCards() {
    const cards = [
        { title: 'Parsed once', body: 'The template is parsed a single time and bound per card.' },
        { title: 'Bound as text', body: body.value },
    ];
    renderCards(cards);
    ssr.textContent = toHTML(cards[1]);
}

function updateComment() {
    rich.innerHTML = cleanHTML(comment.value);
}

body.addEventListener('input', updateCards);
comment.addEventListener('input', updateComment);
updateCards();
updateComment();

index.html

htmlApache-2.030 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Render cards from data through a template</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Render cards from data through a template</h1>
    <label for="body">Body of the last card (anything you type is shown as text)</label>
    <textarea id="body" rows="2">&lt;img src=x onerror="alert(1)"&gt;&lt;script&gt;alert(2)&lt;/script&gt;</textarea>
    <section id="cards" aria-label="Cards"></section>
    <h2>A comment with allowed markup</h2>
    <label for="comment">Comment HTML</label>
    <textarea id="comment" rows="2">I &lt;b>love&lt;/b> this
&lt;a href="javascript:alert(1)">link&lt;/a>&lt;script>steal()&lt;/script></textarea>
    <div id="rich" aria-live="polite"></div>
    <h2>The same template as an HTML string</h2>
    <pre id="ssr"></pre>
  </main>
</body>
</html>