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 = ["hi", "bye"]
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
asked Feb 3, 2011 at 15:33
butterywombat
2,0897 gold badges26 silver badges44 bronze badges
1 Answer 1
have you tried this?
<%=raw @var_data %>
answered Feb 3, 2011 at 15:37
Mauricio
5,8602 gold badges30 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
butterywombat
thanks! that did it. i was trying @var_data.raw instead, which was a nomethoderror.
butterywombat
I didn't find many people having to do this/talk about this though--is it more of a hack or quite common?
Mauricio
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.
Phantomwhale
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
Jason Kim
This is so useful! Thank you. I've been searching for this solution everywhere.
lang-js
varin front of my variable names. (using jquery if that matters)