tpl-stream
v0.0.3
Published
html template library that supports streaming for javascript runtimes
Downloads
19
Maintainers
Readme
tpl-steam
tpl-stream
is a Javascript template library that supports streaming. You can use it in your server, but not only, to generate html: it works everywhere as long as the runtime
implements web streams.
It is very small compared to the alternatives and does not require any build step, while providing very good performances.
Installation
You can install from a package manager like npm by running the command
npm install --save tpl-stream
Or import the module from a CDN:
import {render, html} from 'https://unpkg.com/tpl-stream/src/index.js';
Usage
Basics
You can define a template 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: 'Lorenzofox', classname: 'primary'}))
when rendered, the html string will be '<p class="primary">Lorenzofox</p>'
Interpolated expressions are automatically escaped (for safety) whether they correspond to a text content or to an attribute.
If you wish not to escape a string, you can put it inside an array:
html`<p>${['<span>42</span>']}</p>`
Composition
You can combine several templates to compose more complex templates:
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:'Lorenzofox'})
}));
// <h1>some title</h1><main><p>Lorenzofox</p></main>
Conditionals
When using conditional, via ternary expression for example, make sure all the branches are isomorphic: the templates are compiled for optimization and this is based on the interpretation of the first interpolated value:
// don't
<p>${ foo ? html`<span>42</span>` : ''}</p>
// do
<p>${ foo ? html`<span>42</span>` : html``}</p>
Containers
You can interpolate some containers: Promise, Iterable(Array), Streams(anything that implements AsyncIterator) or Objects These 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>`
Any object container will always be interpreted as a map of attributes (there is no parsing context).
key value pairs whose value is strictly equal to false
are ignored.
html`<button ${{disabled:false, ['aria-controls']:'woot'}}>hello</button>`
// <button aria-controls="woot">hello</button>
render
The render
function takes a template as input and returns a ReadableStream
. The chunks are split every time there is a pending Promise:
<p>foo<span>${43}</span>woot<span>${Promise.resolve('woot')}</span></p>
// chunks: ['<p>foo<span>43</span>woot</span>', 'woot'</span></p>]
You can also render a template as a string, by awaiting the Promise returned by renderAsString
function
Perceived speed
Note that streaming can also improve the perceived speed as the browser renders the HTML (and eventually fetch some resources) while the server has not fully responded to the request. This is the behavior you can observe below: the database has an (exagerated) latency of 1s when the server calls it to fetch the blog posts data. On the left side, the server has already started streaming the first part of the HTML and the browser can already render the upper part of the document while the database is still responding.
You can combine libraries such tpl-stream
with techniques like Out Of Order streaming to improve the user experience even further.
https://github.com/lorenzofox3/tpl-stream/assets/2402022/d0a52057-240f-4ee4-afe7-920acea8a1af