AnApprentice
AnApprentice

Reputation: 110960

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

Upvotes: 5

Views: 3718

Answers (2)

Winfield
Winfield

Reputation: 19145

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>'
}

Upvotes: 2

Fernando Diaz Garrido
Fernando Diaz Garrido

Reputation: 3995

This should work

render :json => render_to_string(normal_options_for_render)

Upvotes: 10

Related Questions