Adam Tuttle
Adam Tuttle

Reputation: 19804

Using Layouts with Express 3.x

All of the guides I've found seem to refer to earlier versions of Express and it's my understanding that this functionality has changed somewhat from 2.x to 3.x. I'm assuming that since npm install express currently installs version 3.0.3 that 3.x is considered stable and ready for production use. (Is that not the case?)

I'd like to use EJS or Kiwi templates, and if possible I'd like to have Underscore available from within templates.

But my first hurdle is getting a layout to render around my content/partial.

Given:

$ express --ejs test

index.js:

exports.index = function(req, res){
  res.render('index', { title: 'test' });
};

I've created layout.ejs, but I can see when I view source that it's not being called.

Have layouts been completely passed off to the template library to deal with in Express 3.x (thus if the template library of choice doesn't implement them, you're SOL)?

If it's still part of Express, how do I configure it? If it must be implemented by the templating library, I don't see instructions for layouts in either the EJS or Kiwi documentation -- does that mean they're not supported at all?

Upvotes: 1

Views: 1254

Answers (1)

chovy
chovy

Reputation: 75666

Use ejs-locals to get layout support (also provides blocks and partials)...as layouts have been removed in express 3.x.

https://github.com/RandomEtc/ejs-locals

Run node app.js from examples and open localhost:3000 to see a working example.

Given a template, index.ejs:

<% layout('boilerplate') -%>
<% script('foo.js') -%>
<% stylesheet('foo.css') -%>
<h1>I am the <%=what%> template</h1>
<% block('header', "<p>I'm in the header.</p>") -%>
<% block('footer', "<p>I'm in the footer.</p>") -%>

And a layout, boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>It's <%=who%></title>
    <%-scripts%>
    <%-stylesheets%>
  </head>
  <body>
    <header>
      <%-blocks.header%>
    </header>
    <section>
      <%-body -%>
    </section>
    <footer>
      <%-blocks.footer%>
    </footer>
  </body>
</html>

Upvotes: 1

Related Questions