I am trying to build an express.js app and I want to pass some data to my main layout. For example, a list of navigation links that I use on every page. I know how to pass data
Why are you not just using global state?
const navbarItems = [{ pageTitle: 'Home' }]
app.get('/', (req, res) => {
res.render('index', navbarItems);
}
A better solution instead of using app.locals
will be to set a middleware that runs before each route.
app.use((req,res,next) => {
res.locals.navLinks = [
// array data
];
next()
});
Will run before any HTTP request and will set the navLinks before every route.
this will cause the navLinks
to be valid only for the request lifetime and won't polute app.locals
. (which will persist throughout the life of the application).
Here you can include file of header & footer inside your each ejs
file
<%- include('<path>/header.ejs') %>
<%- include('<path>/footer.ejs') %>
This is for ejs
view engine
app.set("view engine", "ejs");
I ended up using app.locals like this:
// app.js
app.locals.navLinks = [
// array data
]
I can then use it in my views (including my layout views) as follows:
// views/layouts/main.html
{{#each navLinks}}
<a href="{{ url }}">{{title}}</a>
{{/each}}
You don't send vars to the layout in any special way: whatever you send to the template is accessible in the layout.
You have a few options here: