在我的控制器中,我有:
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
在我看来,我有:
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}
}
渲染视图时,这不起作用,因为我看不到图表。但是,如果我更改了这一行:
label: #{raw @legend},
至:
label: "First Data Set",
视图(和图表)正确呈现。如何在.slim模板内将文本字符串传递到javascript脚本?
最佳答案
您必须引用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}
}
您也可以只用ruby构造整个哈希并将其转换为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
%>