0

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?

Philip7899
  • 4,599
  • 4
  • 55
  • 114
  • [html_safe](http://apidock.com/rails/String/html_safe) - Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed. It is your responsibilty to ensure that the string contains no malicious content. This method is equivalent to the `raw` helper in views. It is recommended that you use `sanitize` instead of this method. It should never be called on user input. – Roman Kiselenko Jul 29 '15 at 21:22
  • You got several answers. If one of them helped in any way, please close the question by choosing one? – Christian Rolle Aug 03 '15 at 13:33

3 Answers3

1

I would use to_json:

//javascript
var lineChartData = {
    labels : <%== @cars.to_json %> 
}
spickermann
  • 100,941
  • 9
  • 101
  • 131
0

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.

Christian Rolle
  • 1,664
  • 12
  • 13
0

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.

Javid Jamae
  • 8,741
  • 4
  • 47
  • 62