Node.js: usare EJS come template engine di Express

Node.js: usare EJS come template engine di Express

EJS (Embedded JavaScript templates) è una valida alternativa a Jade nello sviluppo con Node.js ed Express.

Per prima cosa scarichiamo il package:


npm install ejs

Poi lo impostiamo come template engine in Express:


var express = require('express');
var app = express();

app.set('view engine', 'ejs');

Dobbiamo usare un oggetto le cui proprietà verranno usate come variabili da EJS:


app.get('/', function(req,res) {
	var data = {
		title: 'Home',
		message: 'Hello world'
	};
	
	res.render('views/home', data);
});

Il nostro template, home.ejs, avrà questa struttura:


<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<meta charset="utf-8">
</head>
<body>
<h1><%= message %></h1>
</body>
</html>

L'output finale sarà il seguente:


<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<h1>Hello world</h1>
</body>
</html>

In EJS è possibile usare direttamente JavaScript. Ad esempio:


app.get('/', function(req,res) {
	var data = {
		title: 'Home',
		message: 'Hello world',
		items: ['A','B','C']
	};
	
	res.render('views/home', data);
});


<ul>
	<% for(var i = 0; i < items.length; ++i) { %>
		<li><%= items[i] %></li>
	<% } %>
</ul>	

Output:


<ul>
	<li>A</li>
	<li>B</li>
	<li>C</li>
</ul>

Torna su