1

1st method

res.render('index',{people:people});

2nd method

res.locals.people = people;
res.render('index');

I saw there's 2 ways to pass variable to view, what's the different btw above method?

1 Answer 1

1

I think they are the same for pass variable to render template, but there is a difference. You can use res.locals to pass variable from serval middlewares.

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use(function(req, res, next){
  res.locals.user = req.user;
  res.locals.authenticated = ! req.user.anonymous;
  next();
}); 

From this code, you pass req.user to next middleware.

Sign up to request clarification or add additional context in comments.

2 Comments

so it's better to use res.locals? because it's more flexible?
I think if you want to render the template, i think res.render('index',{people:people}); is a better way.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.