Skip to content

lorenzofox3/tpl-stream

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

58 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tpl-stream

install size

tpl-stream is a Javascript template library that supports streaming. It helps to generate HTML in a server environment, but not only. It requires a runtime that implements web streams and iterator helpers (Node.js >= 22, modern browsers).

It is very small compared to the alternatives and does not require a build step, while providing very good performance. More details can be found in this blog post

Installation

The library can be installed from a package manager like npm by running the command

npm install --save tpl-stream

Or imported from a CDN:

import {render, html} from 'https://unpkg.com/tpl-stream/src/index.js';

Usage

Basics

A template is defined using the html tagged template:

import {html, renderAsString} from 'tpl-stream';

const Greeting = ({name, classname}) => html`<p class="${classname}">${name}</p>`;

const htmlString = await renderAsString(Greeting({name: 'world', classname: 'primary'}));
// '<p class="primary">world</p>'

Interpolated expressions are automatically escaped whether they correspond to text content or an attribute value.

Raw HTML can be inserted with the raw function. This is the only way to bypass automatic escaping, making unsafe interpolations explicit:

import {html, raw, renderAsString} from 'tpl-stream';

html`<p>${raw('<span>42</span>')}</p>`

Composition

Templates compose by nesting — any interpolated value can itself be a template:

const Tpl1 = ({title, content}) => html`<h1>${title}</h1><main>${content}</main>`;

const Tpl2 = ({name}) => html`<p>${name}</p>`;

const htmlString = await renderAsString(Tpl1({
    title: 'some title',
    content: Tpl2({name: 'world'}),
}));

// <h1>some title</h1><main><p>world</p></main>

Containers

Interpolation supports several containers: Promise, Iterable (Array), Streams (anything implementing AsyncIterator), or plain objects. Containers must contain a template, a string, or another container.

html`<ul>${['foo', 'bar'].map(str => html`<li>${str}</li>`)}</ul>`

// or

html`<p>${Promise.resolve(html`<span>42</span>`)}</p>`

A plain object is always interpreted as a map of HTML attributes. Key-value pairs whose value is strictly false are omitted.

html`<button ${{disabled: false, ['aria-controls']: 'woot'}}>hello</button>`

// <button aria-controls="woot">hello</button>

render

The render function takes a template and returns a ReadableStream. Chunks are flushed at every async boundary (Promise or async iterator):

const stream = render(html`<p>foo<span>${Promise.resolve('bar')}</span></p>`);

// chunks: ['<p>foo<span>', 'bar</span></p>']

renderAsString collects all chunks into a single awaited string:

const html = await renderAsString(template);

Perceived speed

Streaming improves perceived speed because the browser can start rendering and fetching sub-resources while the server is still generating the rest of the page.

The example below has an (exaggerated) 1s database latency. On the left, the server streams the initial HTML immediately so the browser can render the page header and fetch stylesheets before the data arrives.

This library pairs well with techniques like Out Of Order streaming for even better user experience.

side-by-side.mp4

About

html template library that supports streaming for javascript runtimes

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors