html_safe is not working in rails to javascript

2.6k Views Asked by At

I have an array of strings declared in my controller that I need to use in a js file. Here is my code:

#controller
@cars = current_user.cars.completed.collect{|c| c.name.titleize }
puts "#{@cars.inspect}"

The puts returns:

["Presentation 2", "Presentation 1"]

I now need to use the array in javascript, so I do:

//javascript
var lineChartData = {
    labels : <%= @cars %> 
}

The javascript is not working though because the browser is reading it as:

//javascruot
var lineChartData = {
    labels : [&quot;Presentation 2&quot;, &quot;Presentation 1&quot;], 
}

I have tried using html_safe like this:

#controller
@cars = current_user.cars.completed.collect{|c| c.name.titleize.html_safe }
puts "#{@cars.inspect}"

but it has no effect. How do I get the quotes to work properly?

3

There are 3 best solutions below

0
Christian Rolle On BEST ANSWER

Although I don't advise to inject Ruby variables into JavaScript directly using the OutputSafetyHelper#raw works:

//javascript
var lineChartData = {
  labels : <%= raw @cars %> 
}

I suggest to embed those Strings into HTML and fetch them with JavaScript.

1
spickermann On

I would use to_json:

//javascript
var lineChartData = {
    labels : <%== @cars.to_json %> 
}
0
Javid Jamae On

It seems like you're generating a JS view using ERB. I would recommend not mixing ERB with JS like this. Try using a tool like Gon which allows you to set the variable onto a Ruby object in the controller, and allows you to reference the data in your JS using a Javascript object. The advantage to this approach is that you can write pure JS and keep it in the assets directory. Then you can take advantage of the asset pipeline: minimizing, uglifying, coffee script, etc. Pure JS in the assets directory is also more easily tested using a JS testing framework like Jasmine.