When you are going to use EJS in express framework , you should consider template / layout structure .

you may use ejs-locals or ejs-mate for Express 3.X . But if you are using latest or Express 4.X those two npm would not work . You may get Layout Undefined | layout is not a function errors

The only solution is to use express-ejs-layouts node package .  This will work perfect with express 4.X .

Follow the instructions to make it work

$ npm install express-ejs-layouts --save

in your app.js 

var expressLayouts = require('express-ejs-layouts');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

/* GET users page. */
router.get('/', function(req, res, next) {
 res.render('users', { title: 'Express template test ' , layout: "layout.ejs"}); // Specify layout file for different page (e.g about-us , dashboard )
});

Create layout.ejs in your view folder & put this text

<!DOCTYPE html>
<head>
 <title><%= title %></title>
 <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
 <body>
 <h1>Come from layout  page </h1>
 <h1><%= title %></h1>
 <%- body %>
 </body>
</html>

Create users.ejs inside your view folder 

<div>
 User Page  Template test . Come from view page 
</div>


Result (run $ node app.js & navigate to /users )

<!DOCTYPE html>
<head>
 <title>Express template test</title>
 <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
 <body>
 <h1>Come from layout page </h1>
 <h1>Express template test</h1>
 <div>
 User Page  Template test . Come from view page 
 </div>
 </body>
</html>




ejs layout is not Undefined | ejs template is not working | layout Undefined | layout is not a function
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *