Kitten

Reference sections

You work with HTML in Kitten using Kitten’s html tagged template string format that is exposed at kitten.html.

e.g., Here’s a simple page route that prints ā€œHello, world!ā€:

export default function () {
  return kitten.html`
    <h1>Hello, world!</h1>
  `
}

Put the above code into a file called index.page.js (or index.page.ts), run kitten in that directory, and navigate to https://localhost in your browser to see it work.

To learn more about Kitten HTML, see the Dynamic Pages tutorial.

Kitten has a semi-forgiving HTML parser.

Kitten uses regular JavaScript tagged template strings for HTML templates (kitten.html). So the way you get dynamic values into templates is through string interpolation.

String interpolation, without guardrails, is the easiest way to open your web app up for Cross-Site Scripting (XSS) / injection attacks. So Kitten does everything it can to make sure that values are interpolated safely everywhere.

Kitten treats all interpolated values (anything within a ${…}) as text, and ensures that each one is safe for the location the interpolation targets.

HTML created using kitten.html is trusted and kept as HTML when interpolated into other HTML templates.

All other values are escaped by default so that untrusted content cannot add markup or execute code on your page.

If you have a value you trust (e.g., because you’re sure you created it or that you’ve otherwise manually sanitised it), you can tell Kitten ā€œI trust and vouch for this value so interpolate it as-isā€ by calling the kitten.markAsTrusted() method on the value.

When interpolating array values, the behaviour depends on the location of the interpolation:

Here are some examples of HTML being generated and interpolated into templates:

kitten.html`<ul>${items.map(item => kitten.html`<li>${item}</li>`)}</ul>`
kitten.html`<p>${isNew ? kitten.html`<b>new</b>` : ''}</p>`

The return value of kitten.html is considered markup in text nodes only. In an attribute, a script, or tag position, it is joined, if necessary (if it has multiple top-level DOM nodes) and treated like a string. (Its type, however, is not String, so to call a string method on such an interpolated value, you must cast it, i.e., String(myKittenHtml).)

To safely interpolate untrusted markup into your page (e.g., from other people, an API, etc.), use the kitten.safelyAddUntrustedHtml method.

To join kitten.html values, do not use the + operator, as that will give you a plain string, which is escaped. Instead, place them in an array and interpolate the array into your page (e.g., [someHtml, someOtherHtml]).

Values interpolated into JavaScript attributes (on*, hx-on*, Alpine’s @, :, and x- attributes, or following the javascript: prefix of a URL attribute) or into scripts must either be a number, a boolean, null, or a value from the kitten.markAsTrusted() method. Anything else, including a string, an array, an object, and undefined, throws when the page renders.

If you want to interpolate a string into an HTML attribute, put it in a data-* attribute and read it back in the handler.

e.g.,

kitten.html`<button data-name=${name} @click='greet($el.dataset.name)'>Greet me!</button>`

kitten.html`<button data-name=${name} onclick='greet(this.dataset.name)'>Greet me!</button>`

kitten.html`<script id='js' data-post-id=${postId}>go(document.getElementById('js').dataset.postId)</script>`

The kitten.markAsTrusted(value) method takes a string or an array of strings and marks them as trusted.

Interpolating a trusted value into kitten.html inserts the value without escaping it and bypasses all security checks in text and scripts. In attribute position it is attribute source, except on a component tag or next to other text, where it must be one attribute name, as a string must. In an attribute value it skips the URL and JavaScript checks and is escaped like any attribute value. In tag position it must be one element name, as a string must. Only pass it a string you wrote or trust.

import fs from 'node:fs'
const logo = fs.readFileSync(new URL('./logo.svg', import.meta.url), 'utf-8')
kitten.html`<a href='/'>${kitten.markAsTrusted(logo)}</a>`

You can pass an object to the data, hx-vals, hx-vars, hx-headers, and hx-request attributes, and to a script of type application/json, application/ld+json, importmap or speculationrules. Kitten writes it as JSON, and htmx or your own JSON.parse() call reads it back as plain data. Nothing inside it ever runs.

kitten.html`<button name='deletePost' data=${{ id: post.id }} connect>Delete</button>`
kitten.html`<script type='application/json' id='post'>${{ postId, title }}</script>`

You cannot pass an object to x-data, x-bind or any other Alpine.js attribute. Alpine runs some of the strings inside those objects as code: an init or destroy property of x-data, and every property of an x-bind object. If one of those strings came from another person, Alpine would run their text. So Kitten refuses an object there, the same way it refuses a string. Put each value in a data-* attribute and read it from $el.dataset inside the Alpine expression:

kitten.html`<div data-name=${name} x-data='{ name: $el.dataset.name, open: false }'>`

In a JavaScript attribute, a script, the data attribute, or an hx- object attribute, a kitten.markAsTrusted value is code, inserted as written, and so is a kitten.js result. So is a string spread under a JavaScript attribute name, the data attribute, or the hx- object attributes when it was written in the template on the component’s tag (see Spreads). kitten.js takes no interpolated value. A string in the filter of the trigger or hx-trigger attribute (click[…]), or in the morph configuration of the morph, swap, hx-swap, hx-swap-oob, or swap-target attribute (morph:…, config:…), throws. Put such a string in a data-* attribute.

A URL attribute (href, src, action, formaction, poster, and the other single-URL attributes) whose scheme comes from a value, or from a spread of a value that was not written in the template on the component’s tag, must not be javascript:; such a value renders as #kitten-url-scheme-not-allowed. A javascript: URL from another person ran when clicked. Any other scheme is handed to the browser or the operating system, as an https: link to any site is, so a data: image, a tel: number, or your app’s own scheme renders as written. A scheme written in the template, such as href='file://${path}', is unchanged, and so is one written in the template on a component’s tag when the component spreads its props; after javascript:, a value follows the rule for JavaScript attributes. A component that renders a prop as the whole URL (href=${props.href}) renders a javascript: value as #kitten-url-scheme-not-allowed even when you wrote it on the component’s tag; pass it to the kitten.markAsTrusted() method where you write the tag.

A string in attribute position (<button ${value}>) must be one attribute name. true, a number, and an object throw; false, null, undefined, and the empty string render nothing. For attribute source, pass a kitten.markAsTrusted value (${kitten.markAsTrusted('disabled hidden')}); for values, pass a spread (...${{ href: url }}). On a component tag, a value in attribute position must be one attribute name, including a kitten.markAsTrusted value.

A value in tag position (<${tag}>) must be a component or one element name. false, null, undefined, and the empty string render the children alone; any other value throws. Every element name is accepted there, script included; never let other people choose the tag.

A component receives its props as written and escapes them when it renders them. A prop that mixes text and a value arrives as one string. A .fragment.md file inserts each value as kitten.html does; markup there must be a kitten.html result or a kitten.markAsTrusted value.

A string spread onto an element under a JavaScript attribute name (on*, hx-on*, @, :, x-) or an object attribute name (data, hx-vals, and the others) throws unless it was written in the template on the component’s tag or passed to the kitten.markAsTrusted() method. A component that forwards its props with ...${props} still forwards a handler written on its tag, such as <${Button} onclick='save()' />. A record from a request cannot set one: <${Card} ...${record} /> throws when record has an onclick string.

A value in the style or srcdoc attribute is escaped twice. A quote, <, or > in it reaches the CSS or the frame as an entity; for a value you trust, pass a kitten.markAsTrusted value, which is escaped once. kitten.css refuses a value containing <.

Kitten does not check a value that a handler reads from the dataset property. Alpine’s $watch method, an x-bind object, and a bound :on* attribute run such a value as code, and the x-html attribute and the innerHTML property render it as markup.

You’ll notice in the Hello, world! example that we returned just a <h1> tag instead of the full HTML structure for the page.

Kitten has a default template that creates the boilerplate of an HTML page for you (the whole structure, starting with <!doctype html><html lang='…'><head>…, etc.)

To add to parts of this template you can use two mechanisms:

  1. The <page> tag
  2. Special page slots

A head slot overrides Kitten’s own head tags one property at a time; see Special page slots.

The page tag takes the following attributes:

These customise the <html> tag:

These customise the <head> tag:

These customise the <body> tag:

These attributes trigger library includes:

Libraries like htmx, idiomorph, etc., are automatically added to live pages (stateful pages, and stateless pages that export event handlers). In other words, in daily usage, you should not have to specify the htmx, idiomorph, or ws attributes manually.

These attributes customise other Kitten-specific behaviour:

See the Syntax Highlighting section for more details.

Kitten moves the contents of a <content for='…'> tag out of its place in your page and into a slot in Kitten’s page template.

Use the slot property names on the kitten.page object as for values:

kitten.page nameValueWhere the content goes
htmlHTMLIn place of the opening <html lang='…'> tag
headHEADAt the end of <head>, before the styles collected from your page
startOfBodySTART_OF_BODYAt the start of <body>, before your page
endOfBodyEND_OF_BODYAt the end of <body>, after Kitten’s own elements

These aliases have the same values: HTML and Html; HEAD and Head; START_OF_BODY, StartOfBody and startofbody; END_OF_BODY, EndOfBody and endofbody.

(Kitten tries to be forgiving.)

Although not recommended, you can also provide the value directly as a string literal. e.g., for='HEAD'. If doing this, note that the value must be all uppercase and, when it contains multiple words, must be underscore-separated. e.g., for='head' does not match the HEAD slot, and its content is not rendered.

You can target the same slot from several <content> tags. Their contents are added in the order they appear in the source.

A head slot overrides properties in Kitten’s own default head tag. (It doesn’t overwrite the entire default head tag.) In other words, if the contents of a head slot contain <title>, viewport, icon or charset, Kitten replaces its own default tag with the one provided. Other properties are still added from a <page> tag, if one exists. And any not overridden property falls back to Kitten’s defaults.

For example, this page sets its title in the head slot:

export default () => kitten.html`
  <h1>Hello</h1>
  <content for='${kitten.page.head}'>
    <title>Special page slots</title>
  </content>
`

See the special page slots tutorial.

Kitten loads client-side libraries used by your page (htmx, Alpine.js, etc.) in the page’s <head> with the defer attribute. This means they don’t block your page from rendering. It also means none of them exist until the browser parses the whole page.

If a script uses a Kitten library, or anything that another script defines, make it a module:

<script type='module'>
  htmx.config.scrollBehavior = 'smooth'
</script>

Modules, inline or loaded via the src attribute, run after the libraries, in the order they appear on the page. By the time they run, the whole page is ready.

A plain <script> runs as soon as the browser parses it, before any libraries exist. One use case for such scripts might be to include third-party libraries or widgets.

The above script execution rules hold true regardless of where the script is physically-located on the web page, including in the head, startOfBody, and endOfBody special page slots. The slots change where your content goes, they do not determine when scripts in your content are run by the browser.

Once all modules have run, the browser fires the DOMContentLoaded event and the page becomes active: Alpine.js starts, htmx attributes start working, and the page’s socket starts connecting.

Note that a module’s top-level declarations are private to it. If your markup needs to refer to a value from a module (e.g., from an onclick handler, as in the example below), add it to the globalThis object:

<script type='module'>
  globalThis.greet = () => alert('Hello!')
</script>

<button onclick='greet()'>Greet</button>

Including custom client-side code in your server-side page files (.page.js files) is cumbersome. Since your kitten.html templates are already JavaScript template strings, you will have to escape certain bits of code (e.g., code that interpolates values at runtime in the client) and you have to remember to use a module script, as you saw above. Kitten provides you with a simpler convention with its client scripts feature.

You can put a page’s client-side code in a .client.js (or .client.ts) file with the same name as the page (e.g., index.client.js for index.page.js or about.client.js for about.page.js). This is known as a client script file.

Kitten loads a client script file as a module after the libraries, so you don’t have to add a <script> tag for it.

You also don’t have to worry about escaping any code.

While you cannot interpolate server-side values directly into client-side scripts, you can interpolate them into data-* attributes in DOM elements in your server-side pages and read them back from your client side script:

index.page.js:

export default () => kitten.html`
  <p id='rendered' data-time='${new Date().toISOString()}'></p>
`

And index.client.js:

const rendered = document.getElementById('rendered')
const time = new Date(rendered.dataset.time).toLocaleTimeString()
rendered.textContent = `The server rendered this page at ${time}.`

To run code once the page is active, use await kitten.ready.

On a live page, the kitten.ready promise resolves when the page’s socket opens, so the kitten.trigger() method and streamed updates work from that line on. On any other page, it resolves at the DOMContentLoaded event. (If you send a message before the socket opens, Kitten queues it and sends it when the socket opens.)

To configure a library before the page becomes active, do it before the await.

For example, index.client.js:

htmx.config.scrollBehavior = 'smooth'

await kitten.ready

const status = document.getElementById('status')
status.textContent = 'Ready'
kitten.trigger(status, 'ping')

Just like everywhere else in Kitten, you can also write your client scripts in TypeScript. When you do, Kitten will automatically transpile it and serve it as JavaScript for you. Just remember to give it the client.ts extension instead (e.g., index.client.ts). Also see: TypeScript.

A navigation action that swaps just the body of a page (e.g., a link with the hx-boost attribute or a response with the HX-Location header) preserves the current page’s libraries and client script. If the page you’re navigating to requires different libraries, its own client script, or a page socket, use full navigation instead.

Kitten serves any .js or .ts file that isn’t a route or a dependency (see Valid file types) to the browser. Put server-only code that isn’t a route, a component, or a layout in a .script.js or .script.ts file to avoid it being served as client-side JavaScript.

Kitten gives you a simple-to-use event-based HTML over WebSocket implementation called Streaming HTML (because you’re streaming HTML updates to the client) that you can use to build web apps.

See the Streaming HTML tutorial for details, and Event handlers for the rules of event handling.

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.