2012-03-07 77 views
20

我想寫在我看來,一個開關情況:Rails的切換情況下,在視圖

<% @prods.each_with_index do |prod, index|%> 
    <% case index %> 
     <% when 0 %><%= image_tag("#{prod.img}", :id => "one") %> 
     <% when 1 %><%= image_tag("#{prod.img}", :id => "two") %> 
     <% when 2 %><%= image_tag("#{prod.img}", :id => "three") %> 
    <% end %> 
<% end %> 

但它不工作。我必須在每行中添加一個<% end %>嗎?有任何想法嗎 ? 謝謝!

回答

54

叫什麼你應該拉你的第一when到同一塊case

<% @prods.each_with_index do |prod, index|%> 
    <% case index 
    when 0 %><%= image_tag prod.img, :id => "one") %> 
    <% when 1 %><%= image_tag prod.img, :id => "two") %> 
    <% when 2 %><%= image_tag prod.img, :id => "three") %> 
    <% end %> 
<% end %> 
4

首先,您應該真正考慮將此功能抽象爲輔助方法,以避免邏輯混淆視圖。其次,由於erb解析代碼的方式,在ERB中使用case語句有點棘手。嘗試代替(沒有測試過,因爲我沒有在手邊此刻紅寶石):

<% @prods.each_with_index do |prod, index|%> 
    <% case index 
    when 0 %> 
     <%= image_tag("#{prod.img}", :id => "one") %> 
    <% when 1 %> 
     <%= image_tag("#{prod.img}", :id => "two") %> 
    <% when 2 %> 
     <%= image_tag("#{prod.img}", :id => "three") %> 
    <% end %> 
<% end %> 

this線程獲取更多信息。

1

我想在ERB中,你必須把條件放在事件的下面。就像這樣:

<% @prods.each_with_index do |prod, index| %> 
    <% case index %> 
    <% when 0 %> 
     <%= image_tag("#{prod}", :id => "one") %> 
    <% when 1 %> 
     <%= image_tag("#{prod}", :id => "two") %> 
    <% when 2 %> 
     <%= image_tag("#{prod}", :id => "three") %> 
    <% end %> 
<% end %> 

Ruby支持的情況下,whens與當時的關鍵字一行的條件,但我不認爲再培訓局能正確解析。例如:

case index 
    when 0 then "it's 0" 
    when 1 then "it's 1" 
    when 2 then "it's 2" 
end 
17

不要在您的意見中放置太多邏輯。

我想補充一個幫手

def humanize_number(number) 
    humanized_numbers = {"0" => "zero", "1" => "one"} 
    humanized_numbers[number.to_s] 
end 

比你可以從視圖與

<%= image_tag("#{prod.img}", :id => humanized_number(index)) %> 
+1

是的,它更好!謝謝 ! – Maxxx 2012-03-07 15:01:44

+0

+1實際上提供了一個幫手的方法,而不僅僅是演講! – 2012-03-07 15:05:43

3

您還可以使用<%- case index -%>語法:

<% @prods.each_with_index do |prod, index| %> 
    <%- case index -%> 
    <%- when 0 -%><%= image_tag prod.img, :id => "one") %> 
    <%# ... %> 
    <%- end -%> 
<% end %> 
2

這對我有幫助。

<i class="<% 
    case blog_post_type 
    when :pencil %>fa fa-pencil<% 
    when :picture %>fa fa-picture-o<% 
    when :film %>fa fa-film<% 
    when :headphones %>fa fa-headphones<% 
    when :quote %>fa fa-quote-right<% 
    when :chain %>fa fa-chain<% 
    end 
%>"></i> 
相關問題