3

I'm trying to embed data I have defined in my controller in my view. in view.html.erb:

<script>
some_var = <%= @var_data %>
some_ints = <%= @int_data %>
</script>

in my controller:

@var_data = ['hi', 'bye']
@int_data = [1,2,3,4]

however, when I view the generated html file, it looks like

<script>
some_var = [&quot;hi&quot;, &quot;bye&quot;]
some_ints = [1,2,3,4]
</script>

ie the ints are fine but all the quotes got escaped. I tried

some_var = <%= @var_data.map {|i| i.html_safe} %>

instead but it didn't do anything (and also html_safe didn't work on the whole array). How should I do this?

Thanks

5
  • add ; at the end of the js lines Commented Feb 3, 2011 at 15:41
  • i'm new to js--is it necessary? (also I'm not sure when/if I should be using var in front of my variable names. (using jquery if that matters) Commented Feb 3, 2011 at 16:02
  • oh, i read somewhere ; is only needed if things are on the same line? Commented Feb 3, 2011 at 16:09
  • 1
    despite JS can run without semicolons in the end of line, they are necessary. Watch about the semicolon insertion here youtube.com/watch?v=hQVTIJBZook Commented Feb 3, 2011 at 16:49
  • for the to var or not to var post a new question. Commented Feb 3, 2011 at 16:50

1 Answer 1

7

have you tried this?

<%=raw @var_data %>
Sign up to request clarification or add additional context in comments.

5 Comments

thanks! that did it. i was trying @var_data.raw instead, which was a nomethoderror.
I didn't find many people having to do this/talk about this though--is it more of a hack or quite common?
I think it's quite common, Rails3 escapes html automatically before printing on an erb for security reasons. But there are some use cases (like yours) when you need to display the raw html.
Just spent quite some time looking for this answer, so thanks to poster and answerer ! However, I had to actually use <%= raw @var_data.collect{|c| '"'+c+'"'}.join(",")%> to get the output of "hi", "bye" - using just <%=raw @var_data %> got me just hibye
This is so useful! Thank you. I've been searching for this solution everywhere.

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.