📚 Esempi Incrementali - Template EJS

Questa pagina mostra esempi progressivi di template EJS, partendo dal più semplice al più complesso.

1️⃣ Esempio 1: Nessun Dato

Template EJS senza variabili - equivale a un normale file HTML.

// Server: Non passa nessun dato ctx.body = await ejs.renderFile(filePath, {}); // Template: Non usa variabili <h1>Ciao Mondo!</h1>
Vedi Esempio 1

2️⃣ Esempio 2: Una Variabile

Template che usa una sola variabile.

// Server: Passa UNA variabile ctx.body = await ejs.renderFile(filePath, { nome: 'Mario' }); // Template: Usa la variabile Il tuo nome è: <%= nome %>
Vedi Esempio 2

3️⃣ Esempio 3: Più Variabili

Template che usa più variabili.

// Server: Passa PIÙ variabili ctx.body = await ejs.renderFile(filePath, { nome: 'Mario', eta: 30, citta: 'Roma' }); // Template: Usa tutte le variabili Nome: <%= nome %> Età: <%= eta %> Città: <%= citta %>
Vedi Esempio 3

4️⃣ Esempio 4: Condizionale (if/else)

Template con logica condizionale.

// Server: Passa variabili per if/else ctx.body = await ejs.renderFile(filePath, { autenticato: true, nome: 'Mario' }); // Template: Usa if/else <% if (autenticato) { %> Benvenuto <%= nome %>! <% } else { %> Non sei autenticato. <% } %>
Vedi Esempio 4

5️⃣ Esempio 5: Loop (forEach)

Template con ciclo forEach su array.

// Server: Passa un array ctx.body = await ejs.renderFile(filePath, { prodotti: ['Laptop', 'Mouse', 'Tastiera'] }); // Template: Loop sull'array <% prodotti.forEach(function(prodotto) { %> <li><%= prodotto %></li> <% }); %>
Vedi Esempio 5

💡 Punti Chiave

Regola: Devi passare esattamente i dati che il template usa!