How to edit page after rendered with Node.js?

Asked

Viewed 396 times

1

I need every time a page with a path is rendered to be added a paragraph after the <body> and another paragraph before the </body>.

I’m using Express.js and da to do this by picking up the string return from app.render and after manipulating it rotate a res.write. But this way I would have to repeat the code for all routes and my intention is to do it as if it were a middleware run with single app.use.

  • Just out of curiosity, which template engine is Voce using? Jade?

  • @renatoargh Uso ejs.

  • Does this help? http://stackoverflow.com/questions/21843840/how-does-res-renderview-locals-callback-work-node-js-express-module

1 answer

1

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.

Browser other questions tagged

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