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

3
  • Please post your controller code to show how Story.all is populated. Commented Jan 22, 2014 at 4:40
  • post an example of @stories[0].story_text Commented Jan 22, 2014 at 5:07
  • Story.all is populated through a form using CKEditor. The controller is literally only doing @stories = Story.all I added an example Commented Jan 22, 2014 at 6:01

2 Answers 2

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\" />");
Sign up to request clarification or add additional context in comments.

Comments

0

You are looking for HTMLEntities

8 Comments

I don't quite understand how this would work? I would encode/escape the HTML in my controller and decode it with Javascript in my view? Wouldn't I face the same problem with the quotation marks when decoding? Could you add an example relating to my problem?
why are you doing the output in Javascript? It should be in view script
Can you dynamically insert HTML with view script? I want to click a link and have the HTML inserted into an element
alright, I understand. Are you fetching the model data via AJAX?
No, they're all being passed by the controller to the view at rendering
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.