Adding rendered HTML to JSON Adding rendered HTML to JSON json json

Adding rendered HTML to JSON


Maybe a bit rough (and not 100% super the "Rails way") but working fine for me in a similar situation:

render :text => {:result => "success",                 :document_row => render_to_string(                                  :file => "admin/documents/_document_row",                                  :formats => "html",                                  :layout => false,                                  :locals => {:documentable => documentable})}.to_json

so roughly just generating a hash and use render_to_string to get the html from th _document_row template.


If you use something like KnockoutJS or another javascript data-binding or templating tool, you can have a skeleton 'template' in the page to start with, that gets filled in with camping listings when you make the ajax request.

The way it works is that you have your table or list or whatever of camping listings bound to an array of camping objects in your Knockout model. When you make your ajax request, you just update that array with the json that comes back. When that array is updated, the DOM is automatically updated to show the new listing. This lets your ajax request get the data only and not all the HTML markup, which means fewer bytes over the wire, and you can separate the act of fetching new data from updating the DOM based on that data.