2015-06-27 37 views
0

我使用Ruby on Rails,我想在我的索引視圖中使用Javascript中的Ruby變量。JavaScript中的Ruby on Rails變量無引號

這裏的Ruby代碼:

def kml 

require 'ruby_kml' 

kml = KMLFile.new 
folder = KML::Folder.new(:name => 'Melbourne Stations') 
[ 
    ["Berlin1", 52.520645, 13.409779], 
    ["Berlin2", 52.520645, 13.409779], 
    ["Berlin3", 13.409779, 52.520645], 
].each do |name, lat, lng| 
    folder.features << KML::Placemark.new(
     :name => name, 
     :geometry => KML::Point.new(:coordinates => {:lat => lat, :lng =>  lng}) 
) 
end 
kml.objects << folder 

@kml = kml.render 

return kml 
end 

在這個變量是以下字符串:

<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="http://earth.google.com/kml/2.1"> 
<Folder><name>Melbourne Stations</name> 
<Placemark><name>Berlin1</name> 
<Point><coordinates>13.409779,52.520645</coordinates></Point></Placemark> 
<Placemark><name>Berlin2</name> 
<Point><coordinates>13.409779,52.520645</coordinates></Point></Placemark> 
<Placemark><name>Berlin3</name> 
<Point><coordinates>52.520645,13.409779</coordinates></Point></Placemark> 
</Folder> </kml> 

而且在Javascript我想在下面的代碼使用這個KML:

var vectorLayer = new ol.layer.Heatmap({ 
    source: new ol.source.Vector({ 
     features: (new ol.format.KML({ 
      extractStyles: false 
     })).readFeatures('<%= kml.render.to_json %>',{ 
        dataProjection:'EPSG:4326', 
        featureProjection:'EPSG:3857' 
       }) 
    }) 
}); 

但問題是,在代碼的頂部和底部JavaScript或Ruby創建雙引號和t他Javascript無法用引號讀取它。

那麼我需要做些什麼來解決這個問題呢?

+0

你試過'<%= j kml.render.to_json%>' – zeronone

+0

是的,我試過了。但它不起作用:/ – mark96

+0

嘗試'<%= raw kml.render.to_json%>' –

回答

0

好吧,我解決了自己的問題...:DI剛剛添加下面的JavaScript代碼:

var kml = '<%=raw @kml.to_json %>'; 

kml = kml.replace("\"", ""); 

所以我創建了一個JavaScript變量和剛剛更換的報價......太容易-.-