Vykresľovanie z Node.js
Vykresli šablónu z aplikácie Node.js a ulož HTML do súboru.
Tento skript vykreslí šablónu demo/invoice a uloží výsledok ako invoice.html. Potrebuje Node.js 18 alebo novší, ktorý má vstavaný fetch.
1. Ulož skript ako 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. Spusti ho so svojím API tokenom:
OPENTEMPLATES_TOKEN=YOUR_TOKEN node render.jsSaved invoice.html, 837 characters3. Otvor invoice.html v prehliadači.
Ak je ID šablóny nesprávne, skript vypíše chybu, napríklad:
400 [{"error":"Template not found"}]Pozri si Vykreslenie šablóny a Chyby.