Render templates

@nanoweb/template supports two render modes: string and stream rendering. Each one has its advantages and disadvantages, but rendering to strings is in general easier to use and slightly more resource efficient, whereas rendering to streams can drastically reduce the time to first byte (TTFB).

Render to string

renderToString returns a Promise with a string value. Check out the API documentation to check out all options.

Usage

renderToString(html`Hello, World!`).then(text => console.log(text));

... or with async/await:

const text = await renderToString(html`Hello, World!`);
console.log(text);

Examples

express()
.get('/', async (req, res) => {
res.send(await renderToString(html`Hello, World!`));
})
.listen(3000);

Fastify natively handles promises:

fastify()
.get('/', () => renderToString(html`Hello, World!`))
.listen(3000);

Render to stream

renderToStream returns a Readable, which can be directly consumed by most frameworks (e.g. Express or Fastify). When using streams we need to pay special attention to error handling and header manipulation. Due to the nature of streams some parts of the response can already be sent off to the client before all templates have been processed. Some of these issues can be circumvented by using HTTP Trailers or Redirects. Check out the API documentation to check out all options.

Usage

This will print the rendered result in chunks:

renderToStream(html`Hello, World!`).pipe(process.stdout);

Examples

express()
.get('/', (req, res) => {
renderToStream(html`Hello, World!`).pipe(res);
})
.listen(3000);

If you are sending a stream and you have not set a 'Content-Type' header, Fastify will set it to 'application/octet-stream':

fastify()
.get('/', (request, reply) => {
reply
.type('text/html')
.send(renderToStream(html`Hello, World!`));
})
.listen(3000);