Search code examples
node.jsexpresstemplateshandlebars.js

Can I render html in express without using res.render / return info to the user?


I want to render HTML the same way I render most other pages, with res.render(), which is set to use handlebars.

But I don't want to just return the HTML, I want to put the HTML into an object, along with some other info, and then return that.

I know I could load a new handlebars instance, but I don't want to do that as I need all the helpers and partials. Is there a way to render using the same instance of handlebars that res.render uses, but just returns me the HTML?

I want to do something like this:

router.get('/list', function(req, res, next) {
  Users((err, users)=>{
    if (err) console.log(err);

    var html = res.render('user-list', {
        layout: false,
        users: users,
    });

    res.json({
        html: html,
        otherInfo: otherInfo
    });
  });
});'

But obviously cant do that because res.render will start sending the HTML to the user.

Any tips?

edit: figured it out, just cant accept my own answer


Solution

  • Use req.app to access the express instance, which has the method render, which will return the HTML. The function is asynchronous so you will need to provide a callback, not set it to a variable.

    app.render() docs