Pass variables on all renders

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 a way to always pass a variable to views without necessarily putting them in the second parameter of the render() function?

Thank you.

    
asked by anonymous 18.01.2018 / 17:16

1 answer

1

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

Differences between them.

  • app.locals - The value of properties persists throughout the application life . To use, just:

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

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

Both in views , for example:

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

References:

18.01.2018 / 23:28