Last Updated: February 25, 2016
·
15.28K
· poupougnac

Using EJS engine with Express 3.X / NodeJS

It supposes that you have already a working project with Express 3

Dependency :

var ejs = require('ejs');

Let's configure Express :

app.set('view engine', 'ejs');
app.set('views',__dirname + '/templates');
app.set('view options', { layout:false, root: __dirname + '/templates' } );

 Rendering with Express :

app.get('/page1',function(req,res) {
    var dataEJS = {};
    dataEJS.page_title = 'My Beautiful Title';
    dataEJS.page_body = 'My Beautiful Content';
    res.render('page1.ejs', dataEJS);
});

Rendering with EJS directly with fs module :

app.get('/page2',function(req,res) {
    var dataEJS = {};
    dataEJS.page_title = 'My Beautiful Title';
    dataEJS.page_body = 'My Beautiful Content';
    var ejs_file = fs.readFileSync('templates/page2.ejs', 'utf-8');
    var page_html = ejs.render(ejs_file, dataEJS);
    res.send(page_html);
});

Note that with Express 3, you can include partials directly from an EJS file using :

<%- include partial.ejs %>

the path is relative from the caller not from the views directory