According to the express source code you can pass a callback to the function res.render
, if you don’t pass a callback you may notice that the express itself provides a default callback that invokes res.send
with the result of the rendering.
You can change the rendered string as you want from this callback, but we know that it is very difficult to change the HTML string at hand, in this case you can use a module like Cheerio to make this manipulation.
Applying to all routes
A mechanism to adopt this solution on all routes would be more or less 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 above paragraphs answer your question I would not particularly adopt this solution (I would not think of modifying the answer before sending). I would prefer to use a mechanism in the templates themselves, some kind of include or import
(I don’t know what nomenclature is used in EJS) so that all templates automatically import this additional content. This second approach is less laborious and less prone to error.
Just out of curiosity, which template engine is Voce using? Jade?
– Renato Gama
@renatoargh Uso ejs.
– ropbla9
Does this help? http://stackoverflow.com/questions/21843840/how-does-res-renderview-locals-callback-work-node-js-express-module
– Lollipop