Matt
Matt

Reputation: 2327

How to use partials in Express.js layout?

I have a layout.ejs file that contains my site's basic boilerplate HTML markup: doctype declaration, head, body, footer, the basics...

How would I go about placing the navigation in a separate partial file and including it into this layout? Is there a particular require() or include() function for doing this?

I am using EJS view engine.

Upvotes: 6

Views: 18423

Answers (3)

Emir Mamashov
Emir Mamashov

Reputation: 1168

var hbs = require('express-handlebars');
// view engine setup
app.set('view engine', 'hbs');

app.engine( 'hbs', hbs( {
  extname: 'hbs',
  defaultView: 'default',
  layoutsDir: __dirname + '/views/layouts/',
  partialsDir: __dirname + '/views/partials/'
}));

see: page templates

Upvotes: 0

Kingsley Ijomah
Kingsley Ijomah

Reputation: 3413

I came across similar issue with handlebars template, working with expressjs 4.0

In my app.js:

var hbs = require('hbs');

// register path to partials
hbs.registerPartials(__dirname + '/views/partials');

Then add a partial file to your partials dir:

/views/partials/nav.hbs

You could then call it within e.g index.hbs like so:

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>

  <body>
    {{> nav}}
    ...
  </body>
</html>

Upvotes: 8

Morgan ARR Allen
Morgan ARR Allen

Reputation: 10678

Yes.

<% include path/to/template %>

Documentation here. https://github.com/visionmedia/ejs#includes

Upvotes: 8

Related Questions