8

I am trying to use Express js with .ejs views.

I want to redirect my page to some another page on any event let say "onCancelEvent"

As per Express js documentation,I can do this by using res.redirect("/home");

But I am not able to get res object in my ejs file.

Can anyone Please tell me how to access req and res object in .ejs file

Please help.

Thanks

user1481951
  • 79
  • 1
  • 1
  • 6
  • Generally you want to separate your rendering logic from your application logic. Can you elaborate on why you want to do this? – loganfsmyth Jan 17 '13 at 07:44

2 Answers2

12

Short Answer

If you want to access the "req/res" in the EJS templates, you can either pass the req/res object to the res.render() in your controller function (the middleware specific for this request):

res.render(viewName, { req : req, res : res /* other models */};

Or set the res.locals in some middleware serving all the requests (including this one):

res.locals.req = req;
res.locals.res = res;

Then you will be able to access the "req/res" in EJS:

<% res.redirect("http://www.stackoverflow.com"); %>

Further Discussion

However, do you really want to use res in the view template to redirect?

If the event initiates some request to the server side, it should go through the controller before the view. So you must be able to detect the condition and send redirect within the controller.

If the event only occurs at client side (browser side) without sending request to server, the redirect can be done by the client side javascript:

window.location = "http://www.stackoverflow.com";
Weihong Diao
  • 718
  • 6
  • 12
1

In my opinion: You don't.

It is better to create the logic that determines the need to redirect inside some middleware that happens long before you call res.render()

It is my argument that your EJS file should contain as little logic as possible. Loops and conditionals are ok as long as they are limited. But all other logic should be placed in middleware.

function myFn( req, res, next) {
  // Redirect if something has happened
  if (something) {
    res.redirect('someurl');
  }
  // Otherwise move on to the next middleware
  next();
}

Or:

function myFn( req, res, next) {
  var options = {
    // Fill this in with your needed options
  };

  // Redirect if something has happened
  if (something) {
    res.redirect('someurl');
  } else {
    // Otherwise render the page
    res.render('myPage', options);
  }
}
adamkonrad
  • 6,794
  • 1
  • 34
  • 41
Intervalia
  • 10,248
  • 2
  • 30
  • 60