Agent Wranglers

CSS-20Recommended

Pass data to templates instead of markup

Give every template or component function plain data, such as text, numbers, lists and named options. Callers never pass HTML strings or extra class names into it.

How to do it

The function escapes every text value and builds all markup itself. A variant is a named option, as Change components through variants describes, not a class the caller adds. Shared pieces come from one module each, as Build every repeated piece of HTML from one shared module requires.

Examples

JavaScript example

const escape = text => String(text).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
export const priceTag = ({ name, price, variant = 'default' }) =>
  `<p class="price-tag" data-variant="${escape(variant)}"><span class="price-tag-name">${escape(name)}</span> ${escape(price)}</p>`;

// test
assert.ok(!priceTag({ name: '<script>', price: '4.50' }).includes('<script>'));

Python example

from html import escape

def price_tag(name, price, variant="default"):
    return (f'<p class="price-tag" data-variant="{escape(variant)}">'
            f'<span class="price-tag-name">{escape(name)}</span> {escape(price)}</p>')

# test
assert "<script>" not in price_tag("<script>", "4.50")

How to check

A unit test renders each template with <script> in every text field. The output contains 0 raw <script> tags. No template signature accepts a parameter named html, className or class.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/html-css/html-structure-and-reuse/partials-take-data">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.