Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How can I assemble different parts of a view with Express before sending it back?

How can I assemble different parts of a view with Express before sending it back?

Problem

I have a project and I need to Send back Rendered Html via an AJAX call. I know I can use res.render('myview', {...}); to pass the data back as fully rendered HTML. But I have to render 3 different parts of the page and I want to encapsulate all of those three parts into one response.

So that leaves me with one of two options possibly. Either I can render the view and NOT send it then use res.write to send all the views once they're ready or I can do 3 different AJAX calls. I'd prefer the first one. Any ideas on how to get started?

Problem courtesy of: Shamoon

Solution

  res.header 'Content-Type','application/json'
  res.partial 'partials/categories', {categories: categories}, (err, categoriesHtml) ->
    res.partial 'partials/items', {items: items}, (err, itemsHtml) ->
      htmlResponse = 
        categories: categoriesHtml
        items: itemsHtml
      htmlResponse = JSON.stringify htmlResponse
      res.send htmlResponse

Partial is right!

Solution courtesy of: Shamoon

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How can I assemble different parts of a view with Express before sending it back?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×