SC_Chupacabra
SC_Chupacabra

Reputation: 14357

Node / Express - Multiple Rendered Views in Response

I'm executing an AJAX call and I'd like to return a JSON response with several rendered partial views that I can use to swap out different part of my page. So, for example:

{
    "searchResults": "<div>Some HTML string</div>",
    "paginationBar": "<div>Another HTML string</div>"
}

My application is built on Node / Express with Express-Handlebars as my view engine. My idea is to do something like this inside my route:

if (req.xhr) {

    res.app.render('partials/search/products', {layout: 'ajax'}, function (err, html) {
            res.locals.renderedViews.searchResults = html;
        }
    );

    res.app.render('partials/search/pagination', {layout: 'ajax'}, function (err, html) {
            res.locals.renderedViews.pagination = html;
        }
    );

    res.json(renderedViews);

}

How can I do this

Upvotes: 0

Views: 899

Answers (1)

Evan Shortiss
Evan Shortiss

Reputation: 1658

Your code looks fine if res.app.render is defined, but you need to nest it since the render code may be asynchronous:

  var renderedViews = {};

  res.app.render('partials/search/products', {layout: 'ajax'}, function (err, html) {
    renderedViews.searchResults = html;

    res.app.render('partials/search/pagination', {layout: 'ajax'}, function (err, html) {
      renderedViews.pagination = html;

      res.json(renderedViews);
    });
  });

Upvotes: 2

Related Questions