Reputation: 6639
In my controller, I have:
def view_chart
@legend = "First Data Set"
@labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
@data_set = [100, 300, 200, 500, 250, 175, 500, 100, 300, 200, 500, 250]
end
And in my view, I have:
javascript:
var lineData = {
labels: #{raw @labels.to_json},
datasets: [{
label: #{raw @legend},
backgroundColor: 'rgba(114,102,186,0.2)',
borderColor: 'rgba(114,102,186,1)',
pointBorderColor: '#fff',
data: #{raw @data_set.to_json}
}
This does not work, as I do not see the chart, when the view is rendered. If, however, I change the line:
label: #{raw @legend},
to:
label: "First Data Set",
The view (and chart) render properly. How do I pass a text string, to a javascript script, inside a .slim template?
Upvotes: 0
Views: 1250
Reputation: 102218
You have to quote the output from erb:
javascript:
var lineData = {
labels: #{raw @labels.to_json},
datasets: [{
label: '#{raw @legend}',
backgroundColor: 'rgba(114,102,186,0.2)',
borderColor: 'rgba(114,102,186,1)',
pointBorderColor: '#fff',
data: #{raw @data_set.to_json}
}
You could also just construct the entire hash in ruby and convert it into JSON:
var lineData = <%=
{
labels: @labels,
datasets: [{
label: @labels,
backgroundColor: 'rgba(114,102,186,0.2)',
borderColor: 'rgba(114,102,186,1)',
pointBorderColor: '#fff',
data: @data_set
}]
}.to_json
%>
Upvotes: 3