Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 711
Matt Avatar asked Jul 23 '13 18:07

Matt


People also ask

What is partials in Express js?

Partials are basically just views that are designed to be used from within other views. They are particularly useful for reusing the same markup between different views, layouts, and even other partials. <%- partial('./partials/navbar.ejs') %>

Is Pug better than EJS?

According to the StackShare community, Pug has a broader approval, being mentioned in 230 company stacks & 608 developers stacks; compared to EJS, which is listed in 9 company stacks and 13 developer stacks.


2 Answers

Yes.

<% include path/to/template %>

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

like image 176
Morgan ARR Allen Avatar answered Sep 27 '22 21:09

Morgan ARR Allen


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>
like image 25
Kingsley Ijomah Avatar answered Sep 27 '22 21:09

Kingsley Ijomah