1.1k views
0 votes
To have a templates application-wide variable in Express.js, I have to:

Option 1: Use a global variable
Option 2: Set it in every route
Option 3: Use res.locals
Option 4: Pass it as a parameter to each template

1 Answer

3 votes

Final answer:

To have an application-wide variable in Express.js templates, use the res.locals option.

Step-by-step explanation:

In Express.js, to have an application-wide variable in templates, you can use res.locals option. The res.locals object provides a way to define variables that are accessible in all routes and views of an application.

For example, you can set a variable called 'user' using res.locals.user = 'John Doe'. This 'user' variable can then be accessed in any route or template of your Express.js application.

This approach is recommended as it allows you to have a single definition of the variable that can be used throughout the application, without cluttering your routes or passing the variable as a parameter to each template.

User Abraham Jagadeesh
by
8.1k points