簡體   English   中英

帶有rails 3.1的咖啡腳本中的erb

[英]erb in coffee script with rails 3.1

我想在我的.coffee文件中使用一些 erb,如下例所示

myLatlng: new google.maps.LatLng(<%=@location.latitude %>, <%=@location.longitude %>)

我將locations.js.coffee重命名為locations.erb.coffee

但我仍然收到以下錯誤

Error compiling asset application.js:
ExecJS::ProgramError: Error: Parse error on line 4: Unexpected 'COMPARE'
  (in /Users/denisjacquemin/Documents/code/projects/geolog/app/assets/javascripts/locations.erb.coffee)
Served asset /application.js - 500 Internal Server Error

如果您希望.coffee文件中的 erb 在您的 VIEW 文件夾中,請將您的文件命名為yourfilename.js.coffee ,Rails 仍然會處理 ERB,這很奇怪。

要使其在 Heroku 中工作,請將 coffee-rails 從 Gemfile 中的資產組中移出。

您可能需要將文件重命名為 locations.coffee.erb 以便在咖啡之前處理 erb :)

在 Rails 4 中盡可能堅持使用資產管道,而不是使用js.erb視圖。

Pass variables to the Js using gon or some other technique discussed at: Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file

gon

應用程序/視圖/布局/應用程序.html.erb:

<head>
  <meta charset="utf-8"/>
  <%= include_gon %>

應用程序/控制器/application_controller.rb:

before_filter do
  gon.latitude = 0.1
  gon.longitude = 0.2
end

應用程序/資產/javascripts/locations.js.coffee:

myLatlng: new google.maps.LatLng(gon.latitude, gon.longitude)

此方法更快,因為文件僅在啟動時預編譯一次,由服務器而不是通過 Rails 提供服務,並且在與 Js 的 rest 相同的 HTTP 請求上。

在 Rails 3.2.8 中,我不必將 my.coffee 文件移動到 /app/views。 我只是在文件名中添加了.erb 並將其留在 /app/assets/javascripts 中。 IE。 我變了

/app/assets/javascripts/user_answers.coffee.js to 
/app/assets/javascripts/user_answers.coffee.js.erb

然后這工作:

# Note the level of indentation.
var x = 2;

<% Question.first(2).each do |eq| %>
alert('eq: ' + <%= eq.id %>)
<% end %>

(壓痕級別必須匹配 CoffeeScript,而不是 Ruby。)享受嵌入紅寶石的咖啡。

我同意 Ciro Centelli 不理會資產管道,特別是如果您使用的是 Heroku。 如果您需要執行許多任務,毫無疑問gon很有用,但您也可以在沒有 gem 的情況下執行此操作。 在您的 html 中包括

<%= javascript_tag do %>
    window.latitude = <%=@location.latitude %>
    window.longitdue = <%= @location.longitude %>
<% end %>

在你的咖啡文件中

myLatlng: new google.maps.LatLng(window.latitude, window.longitude)

您通常可以以類似的方式解決其他需求。 例如,如果您不希望咖啡腳本在具有特定 id 的元素上觸發,那么在 html 中使用 erb 僅在您希望它觸發時添加該 id。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM