2

I am somewhat new to node programming and trying to follow some tutorials. They're almost all written for 2.5.x. I've read the migration page for Express but there are no clear working examples for a newbie. My question is addressing the following areas:

  • req.flash()
  • layouts and partials
  • dynamicHelpers

for 'old way' vs. 'new way' examples and not just snippets or additional modules to make the older version code still work as I'd like to work with the new style of working with Express. Thanks in advance.

1 Answer 1

5

As you found the old-way examples already, here are the 'new' ways:

'new' req.flash:

// insert in app.js as middleware, after express.static
app.use(function(req, res, next) {
  var msgs = req.session.messages || [];
  res.locals({
    messages: msgs,
    hasMessages: !! msgs.length
  });
  req.session.messages = [];
  next();
});

// save a message
res.message('error', 'message');

// output
<% if (hasMessages) { %>
  <ul id="messages">
    <% messages.forEach(function(msg){ %>
      <li class="<%= msg.type %>"><%= msg.msg %></li>
    <% }) %>
  </ul>
<% } %>

'new partials':

// install
npm install express-partials

// app.js
var partials = require('express-partials');
app.use(partials());

// usage
<%- body %>

'new' dynamicHelpers:

// middleware
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});

// usage
<%= user %>
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.