Pass variables on all renders

Asked

Viewed 505 times

2

I have an application using Nodejs, Express (and a few more dependencies). I reduced the application to the file below to explain my question:

app js.:

// Dependências.
const express = require('express');

// Criar a instância do express.
let app = express();

// Middlewares.
app.set('view engine', 'ejs');
app.set('views', './public/views');
app.use('/assets', express.static('./public/assets'));

// Rotas.
app.get('/', function (req, res) {
  res.render('index', { title: 'Título' });
});

app.get('/users', function (req, res) {
  res.render('users', { title: 'Título' });
});

app.get('/groups', function (req, res) {
  res.render('groups', { title: 'Título' });
});

app.get('/calendar', function (req, res) {
  res.render('calendar', { title: 'Título' });
});

// Iniciar o servidor.
const port = process.env.PORT || 80;
app.listen(port, function () {
    console.log(`Server listening at port ${port}.`);
});

Note that in all app.get, i passed a variable to the view. This variable is: title.

Is there any way to always pass a variable to the views without necessarily putting them in the second parameter of the function render()?

Thank you.

1 answer

1


Yes, it is possible. You can define local variables using the object app.locals or res.locals.

Differences between them.

  • app.locals - the value of the properties persists throughout the app’s life. To use, simply:

    app.locals.titulo = 'Título do Meu Site';
    app.locals.email_contato = '[email protected]';
    
  • res.locals - properties are only valid for the life of the request. To use, simply:

    app.use(function(req, res, next){
        res.locals.titulo = 'Título do Meu Site';
        res.locals.email_contato = '[email protected]';
        next();
    });
    

Both in the views, for example:

<% console.log(titulo); %>
<% console.log(email_contato); %>

References:

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.