简体   繁体   中英

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.

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 eg index.hbs like so:

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

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

Yes.

<% include path/to/template %>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM