Render cards from data through a template
Render cards from data through an HTML template; untrusted text stays inert, user HTML is sanitised.
Apache-2.0Runs on this page
Package: @awacloud/fw
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
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - 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 andjavascript:links go.
Code
main.js
// 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
<!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"><img src=x onerror="alert(1)"><script>alert(2)</script></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 <b>love</b> this
<a href="javascript:alert(1)">link</a><script>steal()</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>