2011-09-07 19 views
7

我正在使用Ruby on Rails 3.1,並且想知道如何在JavaScript資源中呈現部分內容。呈現資產中的部分

我想做什麼:

# in /app/assets/javascript/cart.js.coffee.erb 
$('a.add_sth').click -> $('.random_container').append('<%= render partial: 'way/to/partial' %>') 

這將導致NoMethodError:

undefined method `render' for #<#<Class:0x007fc54584c6e8>:0x007fc5474cd470> 

如果我寫<%= 2+3 %>,而不是它工作正常,順便說一句。

我認爲問題是資產管道是獨立於默認的ActionView,這就是爲什麼render()在那裏是未知的。無論如何,有沒有辦法讓部分內容呈現?

回答

5

記住,資產意味着靜態數據,如CSS,JS或圖像不會動態更改其內容,使他們能夠更好的緩存和/或導出到CDN。

由於您可以使用ruby代碼運行ERB,因此應始終返回相同的值(因爲它僅在編譯資產時纔會執行)。

這就是爲什麼我猜渲染是不可用內部資產(儘管它可以正確地用於呈現靜態數據)。

簡單的解決方案在這裏:移動你的JS文件到一個視圖,那裏你將能夠使用任何視圖助手。

0

事實上,它適用於我。 你需要做的:

= render 'way/to/partial' 

其中「方式/到/部分」是根據現有的資產目錄的相對路徑。 有線的事情是,在路徑中,你需要忽略資產下的第一級文件夾。

+0

什麼?如何給一個方法提供一個不同的參數?你有沒有一個工作的例子? – ZedTuX

0

這對我有用。 (對於HAML)

= Haml::Engine.new(File.read(File.join(Rails.root, 'app/views/xxxxx','_form.html.haml'))).render(Object.new, :hello => "Hello World") 

而且,添加在文件開頭的依賴需要等更新: 在這種情況下,依賴文件是需要在資產。

//= depend_on xxxxx/_form.html.haml 
1

我有類似的問題,所以我寫了這個render方法,可裏面的資產可以用來渲染ERB局部模板:

# in lib/my_app/erb_helpers.rb 
module MyApp 
    module ERBHelpers 
    class << self 

     def render(partial_path, binding) 
     dir_name, _, partial_name = partial_path.rpartition(File::SEPARATOR) 
     file_name = "_#{partial_name}.html.erb" 
     Erubis::Eruby.new(File.read(File.join(Rails.root, 'app', 'views', dir_name, file_name)).gsub("'", %q(\\\'))).result(binding) 
     end 

    end 
    end 
end 

然後我用它的CoffeeScript文件中是這樣的:

# in app/assets/javascripts/notifications.coffee 
MyApp.notifications.templates = 
    notice: '<%= ::MyApp::ERBHelpers.render 'application/notifications/notice', content: "%content%" %>' 
    alert: '<%= ::MyApp::ERBHelpers.render 'application/notifications/alert', content: "%content%" %>' 

MyApp.notifications.create_elem = (type, content) -> MyApp.notifications.templates[type].replace('%content%', content) 

PS:我測試的Rails 5.0應用