2011-06-26 105 views
0

我是Ruby和HAML的新手,並試圖渲染主HAML文件中的以下部分內容。部分只包含一個if條件。如果條件滿足,我希望if條件返回部分HAML代碼的輸出到主模板,如果不是,則不提供任何內容。如果數組「attachments.each_file」爲空(它不呈現任何我想要的),但是如果它不爲空,它會在嘗試進入if條件代碼時引發錯誤。以下是相關的代碼片段:如何在HAML中渲染僅包含條件塊的部分

錯誤消息:

LocalJumpError in Questions#show 

Showing /questions/_attachments.html.haml where line #1 raised: 

no block given (yield) 

主要HAML模板代碼:

= render "slashbias/questions/attachments", :attachments => @question.attachments, :editing => false 

部分HAML代碼:

- if !attachments.each_file.empty? 
    %dl#attachments_list 
    %dt.header Attached files: 
    %dd 
     -attachments.each_file do |key, file| 
     = link_to file.name, question_attachment_path(question.group, question, file, key) 
     -if editing 
      = link_to t("scaffold.destroy"), remove_attachment_question_path(question, :attach_id => key), :class => "remove_attachment_link" 

回答

2

我相信attachments.each_file在第1行期待一個塊。它不會在有0個文件的情況下拋出錯誤,因爲它永遠不會嘗試任何yield。但是在存在文件的情況下,each_file正在嘗試將yield這些文件添加到塊中,並提高了您看到的錯誤,因爲沒有塊可以屈服。

是否有另一種方法可以讓您測試是否有任何文件?像!attachments.files.empty?attachments.files.count > 0

+0

我認爲你是在點。 each_file需要一個塊 – jaydel

+0

是的,它做到了。我在想什麼,「each_file」聽起來像是一種循環,我應該更清楚! :) – csuwldcat