2012-02-06 21 views
4

我正在編寫一個Rails 3.2.1應用程序,我有一些JavaScript代碼,我想爲單個操作視圖放置。它只是調用一個jquery插件並開始倒計時,但我想用咖啡腳本編寫它,我覺得資產管道是做這件事的正確工具。如何添加特定於操作的資產管道項目?

另外我需要訪問控制器傳遞的變量,如@question我該怎麼做?我已查看coffeebeans寶石,但只適用於:remote=>true表單和鏈接。

+0

看看這個:http://stackoverflow.com/questions/8566129/how-to-namespace-our-js-for-use-with-the-rails-asset-pipeline/8568208#8568208 – 2012-02-06 14:23:50

+0

關於訪問對可變部分,有一個railscast。 [將數據傳遞給Javascript](http://railscasts.com/episodes/324-passing-data-to-javascript)。 =) – 2012-02-20 10:31:36

回答

1

您的問題可以通過不同的方式解決。

添加資產動態

  1. 添加到我們的應用助手下面的方法:

    module ApplicationHelper 
        def include_related_asset(asset) 
        #   v-----{Change this} 
         if !YourApp::Application.assets.find_asset(asset).nil? 
          case asset.split('.')[-1] 
           when 'js' 
            javascript_include_tag asset 
           when 'css' 
            stylesheet_link_tag asset 
          end 
         end 
        end 
    end 
    
  2. 調用輔助方法,在你的layout -file:

    <%= include_related_asset(params[:controller].to_param + '_' + params[:action].to_param . 'js') %> 
    
  3. 爲您的控件創建特定的資產勒勒行動。例如, controller_action.js

使用yield

  1. 添加<%= yield :head%>到您的佈局頭
  2. 包括你的資產從行動的觀點:

    <% content_for :head do %> 
    <%= javascript_include_tag 'controller_action' %> 
    <% end %> 
    

請參閱Rails guides獲取更多信息。


要控制數據傳遞到您的JavaScript,你可以這樣做:

<%= javascript_tag do %> 
     window.error_message = '<%= j error_message %>'; 
    <% end %> 

請參閱RailCast Episode #324瞭解更多信息。