According to the source code you can pass a callback for the res.render
function, if you do not pass a callback you may notice that the express itself provides a default callback that invokes res.send
with the rendering result.
You can change the rendered string as you want from this callback, however we know that it is very difficult to change the HTML string in the hand, in this case you can use a module like cheerio to do this manipulation.
Applying to all routes
A mechanism to adopt this solution on all routes would be something like this;
function alterarResposta(next) {
return function(err, renderedView) {
if(err) {
return next(err);
}
res.modifyResponse = true;
res.renderedView = renderedView;
next();
}
}
app.get('/helloWorld', function(req, res, next) {
res.render('helloWorld', alterarResposta(next));
});
app.get('/fooBar', function(req, res, next) {
res.render('fooBar', alterarResposta(next));
});
// Aqui vem todas as suas outras rotas!
app.use(function(req, res, next) {
if(!res.modifyResponse) {
return res.send(res.renderedView);
}
//Aqui você modifica sua resposta
res.send(res.renderedView);
});
NOTE: You can put the change response function in another file .js
Although the paragraphs above answer your question I would not particularly adopt this solution (I would not think about modifying the answer before sending). I would prefer to use a mechanism in the templates themselves, some kind of include or import
(I do not know which nomenclature is used in EJS) so that all templates automatically import this additional content. This second approach is less labor-intensive and less error-prone.