res.view()

Respond with an HTML page.

Usage

  1. return res.view(pathToView, locals);

Or:

  • return res.view(pathToView);
  • return res.view(locals);
  • return res.view();

Uses the configured view engine to compile the view template at pathToView into HTML. If pathToView is not provided, serves the conventional view based on the current controller and action.

The specified locals are merged with your configured app-wide locals, as well as certain built-in locals from Sails and/or your view engine, then passed to the view engine as data.

Arguments

Argument Type Details
1 pathToView ((string)) The path to the desired view file relative to your app’s views folder (usually views/), without the file extension (e.g. .ejs), and with no trailing slash.
Defaults to “identityOfController/nameOfAction”.
2 locals ((object)) Data to pass to the view template. These explicitly specified locals will be merged in to Sails’ built-in locals and your configured app-wide locals.
Defaults to {}.

Example

Consider a conventionally configured Sails app with a call to res.view() in the cook() action of its OvenController.js.

With no pathToView argument, res.view() will decide the path by combining the identity of the controller (oven) and the name of the action (cook):

  1. return res.view();
  2. // -> responds with `views/oven/cook.ejs`

Here’s how you would load the same view using an explicit pathToView:

  1. return res.view('oven/cook');
  2. // -> responds with `views/oven/cook.ejs`

Finally, here’s a more involved example demonstrating how res.view can be combined with Waterline queries:

  1. // Find the 5 hottest oven brands on the market
  2. Oven.find().sort('heat ASC').exec(function (err, ovens){
  3. if (err) return res.serverError(err);
  4. return res.view('oven/top5', {
  5. hottestOvens: ovens
  6. });
  7. // -> responds using the view at `views/oven/top5.ejs`,
  8. // and with the oven data we looked up as view locals.
  9. //
  10. // e.g. in the view, we might have something like:
  11. // ...
  12. // <% _.each(hottestOvens, function (aHotOven) { %>
  13. // <li><%= aHotOven.name %></li>
  14. // <% }) %>
  15. // ...
  16. });

Notes

  • This method is terminal, meaning it is generally the last line of code your app should run for a given request (hence the advisory usage of return throughout these docs).
  • res.view() reads a view file from disk, compiles it into HTML, then streams it back to the client. If you already have the view in memory, or don’t want to stream the compiled HTML directly back to the client, use sails.hooks.views.render() instead.