Sending Data Payload
A high-performance engine needs fuel, and a dynamic view needs data. Simply rendering a file isn’t enough; we need to inject a payload of variables from our server directly into the template’s combustion chamber to generate a unique response for every request.
The Locals Object
Section titled “The Locals Object”The res.render() method accepts a second argument known as the locals object.
Properties defined on this object do not exist as a single “data” variable inside the view. Instead, the keys of this object are unpacked and exposed as distinct local variables available to the template.
File: /thingRouter.js
const things = [ { id: 1, name: "Thing 1", description: "Description 1", active: true }, { id: 2, name: "Thing 2", description: "Description 2", active: false }, { id: 3, name: "Thing 3", description: "Description 3", active: true },];
thingRouter.get("/", (req, res) => { // Define the data payload const viewData = { title: "EJS Demo - Thing List", things: things, }; // Pass the payload as the second argument // The view will now have access to 'title' and 'things' variables directly res.render("things", viewData);});In this example:
- The view engine receives
viewData. - It extracts
titleandusers. - Inside
users.ejs, you can referencetitlesimply astitle, notviewData.title.