It is necessary to pass the function reference to the View context. You can pass the function as a parameter in the same way you send data to the View, for example: res.render('myView', { formatDate })
.
Another way is to use the app.locals
or res.locals
to provide the function within your view. The difference is in the life cycle. The app.locals
persists throughout the application throughout its life, already the res.locals
persists only during the lifecycle of a Sponse. See an example:
function formatarValor(entrada) {
return entrada.toUpperCase();
}
// Com a linha abaixo a função "formatarValor" fica disponível dentro da view
app.locals.formatarValor = formatarValor;
app.get('/', (req, res) => {
var dados = ['valor 1', 'valor 2', 'valor 3', 'valor 4'];
res.render('myView', { dadosDaView: dados });
});
I wrote a short text about this scenario: https://medium.com/@Marcelo.vismari/nodejs-express-ejs-como-usar-funcoes-durante-renderizacao-f51122e1eaca
Voce is sending the function
formDate
as an object parameter in the methodrender()
?– Cmte Cardeal
@Cmtecardeal I’m not doing that, I’ve been testing here now this way.
– Brandon Marcos
@Cmtecardeal, I tested it the way you said, but I couldn’t get to the point of doing it right. I did as follows, res.render (I PUT MY FUNCTION IN HERE). also did res.render(formatDate(str)) calling the function inside the render, but it did not work.
– Brandon Marcos
Voce placed the function inside the object? like this: res.render('sua_view', { formDate: formDate }; ?
– Cmte Cardeal
Friend you can’t just call backend functions like this... you need to send it somehow to your template. As @Cmtecardeal suggested
res.render('./templates/customers/customer', { formDate: formDate })
– Rubens Barbosa