Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails passing HTML as JSON and then rendering

is there a way to pass HTML in a JSON object with Rails so you can render the the JSON object as HTML, versus as a string. meaning not seeing the text

but there actually being a paragraph tag/html style.

Thanks

like image 209
AnApprentice Avatar asked Feb 26 '11 23:02

AnApprentice


2 Answers

This should work

render :json => render_to_string(normal_options_for_render)

like image 122
Fernando Diaz Garrido Avatar answered Nov 19 '22 16:11

Fernando Diaz Garrido


Are you trying to dynamically inject HTML content via a JSON responses or return JSON data with HTML content?

If you're looking to include structured JSON-like data with HTML to be rendered, you should consider using HTML data attributes like so:

<ul id="vegetable-seeds">
  <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
  <li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
  <li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
</ul>

If you're trying to return HTML markup inside your JSON, you can embed the HTML as a string object and re-ify it into the DOM during processing:

{
  'foo': 'bar',
  'html': '<p>some markup to be rendered</p>'
}
like image 43
Winfield Avatar answered Nov 19 '22 18:11

Winfield