Spanish Total.js
English
Documentation For AI agents
Contents

Render from Node.js

Render a template from a Node.js app and save the HTML to a file.

.md GitHub

This script renders the demo/invoice template and saves the result as invoice.html. It needs Node.js 18 or newer, which has fetch built in.

1. Save the script as render.js:

const fs = require('fs');

const URL = 'https://templates.example.com/';
const TOKEN = process.env.OPENTEMPLATES_TOKEN;

async function render(id, data) {
    const response = await fetch(URL, {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-token': TOKEN },
        body: JSON.stringify({ id, data })
    });
    if (!response.ok)
        throw new Error(response.status + ' ' + await response.text());
    return response.text();
}

render('demo/invoice', {
    number: '2026-003',
    customer: 'Jane Doe',
    items: [{ name: 'Consulting', price: 300 }, { name: 'Support', price: 120 }],
    total: 420
}).then(function(html) {
    fs.writeFileSync('invoice.html', html);
    console.log('Saved invoice.html,', html.length, 'characters');
}).catch(function(err) {
    console.error(err.message);
    process.exit(1);
});

2. Run it with your API token:

OPENTEMPLATES_TOKEN=YOUR_TOKEN node render.js
Saved invoice.html, 837 characters

3. Open invoice.html in your browser.

If the template ID is wrong, the script prints the error, for example:

400 [{"error":"Template not found"}]

See Render a template and Errors.

Made in Europe