0

I want to take some Rails models passed into a view and render them.

e.g.

In the controller

@stories = Story.all

In the view

$('.story-text').html("#{raw @stories[0].story_text}");

But the HTML string contains " and '. The HTML is thus not contained entirely in a string and the Javascript fails to run.

e.g. it becomes

$('.story-text').html("<img src="/example.jpg" />");

Which causes an error.

How can I accomplish this? Is there triple quotes like in Python that I can use in Javascript?

EDIT Example of @stories[0].story_text

<p>This is some example text</p><img src="/example.jpg" />

It is stored in the database as a text type

Michael Johnston
  • 2,364
  • 2
  • 27
  • 48

2 Answers2

1

Rather than raw, use escape_javascript to escape your string suitably for embedding in javascript. It is aliased to j, so this in your Haml view:

$('.story-text').html("#{j @stories[0].story_text}");

results in this javascript being generated:

$('.story-text').html("<p>This is some example text<\/p><img src=\"/example.jpg\" />");
matt
  • 78,533
  • 8
  • 163
  • 197
0

You are looking for HTMLEntities

Raj
  • 22,346
  • 14
  • 99
  • 142