Spanish Total.js
Español
Documentación Para agentes de IA
Contenido

Generar desde Node.js

Genera una plantilla desde una app de Node.js y guarda el HTML en un archivo.

.md GitHub

Este script genera la plantilla demo/invoice y guarda el resultado como invoice.html. Necesita Node.js 18 o posterior, que trae fetch integrado.

1. Guarda el script como 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. Ejecútalo con tu token de API:

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

3. Abre invoice.html en tu navegador.

Si el ID de la plantilla es incorrecto, el script muestra el error, por ejemplo:

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

Consulta Generar una plantilla y Errores.

Hecho en Europa