Node.js - EJS - including a partial
Solution 1:
With Express 3.0:
<%- include myview.ejs %>
the path is relative from the caller who includes the file, not from the views directory set with app.set("views", "path/to/views")
.
EJS v1 includes
EJS v2 includes
(Update: the newest syntax for ejs v3.0.1 is <%- include('myview.ejs') %>
)
Solution 2:
Works with Express 4.x :
The Correct way to include partials in the template according to this you should use:
<%- include('partials/youFileName.ejs') %>
.
You are using:
<% include partials/yourFileName.ejs %>
which is deprecated.
Solution 3:
In Express 4.x
I used the following to load ejs
:
var path = require('path');
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.ejs exists in the app directory
app.get('/hello', function (req, res) {
res.render('index', {title: 'title'});
});
Then you just need two files to make it work - views/index.ejs
:
<%- include partials/navigation.ejs %>
And the views/partials/navigation.ejs
:
<ul><li class="active">...</li>...</ul>
You can also tell Express to use ejs
for html templates:
var path = require('path');
var EJS = require('ejs');
app.engine('html', EJS.renderFile);
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
res.render('index.html', {title: 'title'});
});
Finally you can also use the ejs
layout module:
var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);
This will use the views/layout.ejs
as your layout.
Solution 4:
As of Express 4.x
app.js
// above is all your node requires
// view engine setup
app.set('views', path.join(__dirname, 'views')); <-- ./views has all your .ejs files
app.set('view engine', 'ejs');
error.ejs
<!-- because ejs knows your root directory for views, you can navigate to the ./base directory and select the header.ejs file and include it -->
<% include ./base/header %>
<h1> Other mark up here </h1>
<% include ./base/footer %>
Solution 5:
Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.