2012-07-10 73 views
1

我有一些像這樣的代碼:如何獲取塊的內容以顯示在視圖中?

<% cache "footer_links" do %> 
    <%= cms_snippet_content('footer_links') %> 
<% end %> 

而且我認爲寫一個輔助方法,這樣一:

def cached_snippet_content(snip_id) 
    cache(snip_id) do 
    cms_snippet_content(snip_id) 
    end 
end 

但是,我沒有得到我認爲任何輸出,甚至雖然,我的erb代碼如下所示:

<%= cached_snippet_content "footer_links" %> 

我在做什麼錯?

+0

你能確保'cache'方法返回一個字符串嗎 – gmalette 2012-07-10 14:34:04

+0

Rails 3我猜? – tokland 2012-07-10 18:18:58

回答

1

可以在源極和你在一起,盧克:

# actionpack-3.2.0/lib/action_view/helpers/cache_helper.rb 
def cache(name = {}, options = nil, &block) 
    if controller.perform_caching 
    safe_concat(fragment_for(name, options, &block)) 
    else 
    yield 
    end 

    nil 
end 

這表明cache實施被稱爲來自ERB的意見,而不是助手。另一種實現:

def cache(name = {}, options = nil, &block) 
    if controller.perform_caching 
    fragment_for(name, options, &block) 
    else 
    capture(&block) 
    end 
end 

現在(即使在塊<%= ...>,如果他們輸出的東西)與新的Rails ERB風格使用它:

<%= cache "key" do %> 
    <%= content_tag(:p, "hello") %> 
<% end %> 

我會測試這個仔細地說,可能存在隱藏的角落,我想這將是爲什麼cache還沒有適應Rails 3塊的風格。

0

它看起來像你的幫助器方法中的do塊沒有返回任何東西,因此整個幫助器方法沒有返回任何東西,此後視圖也沒有任何顯示。

也許試試這個:

def cached_snippet_content(snip_id) 
    cache(snip_id) do 
    result = cms_snippet_content(snip_id) 
    end 
    result 
end 
+0

仍然沒有輸出。如果我自己調用cms_snippet_content方法,它會返回內容,所以我猜想問題是以某種方式從緩存中返回結果。 – Geo 2012-07-10 14:05:29

0

試試這個:

def cached_snippet_content(snip_id) 
    a = "" 
    cache(snip_id) do 
    a += cms_snippet_content(snip_id).to_s 
    end 
    a 
end 
相關問題