2012-06-10 32 views
0

使用Rails 3.這是一個前端設計問題。如果上一個元素存在,則添加間隔文本

目標:

Contact | Email | URL 

show.html.erb:

<% if [email protected]? %> 
    <%= @shop.contact %> 
<% end %> 
<% if [email protected]? %> 
    <%= @shop.email %> 
<% end %> 
<% if [email protected]? %> 
    <%= link_to @shop.url, @shop.url, :target => "_blank" %> 
<% end %> 

如何把在|只有當後的以前和元素具有價值?在現階段,如果沒有價值,則不會輸出任何結果。

非常感謝。

回答

1
<% url = link_to(@shop.url, @shop.url, :target => "_blank") if @shop.url.present? %> 
<%= [@shop.contact, @shop.email, url].select(&:present?).join(" | ") %> 

這將創建所有的元件的陣列,選擇那些具有的值(如present?blank?相反),然後通過將它們之間的管道加入其餘陣列中的每個元素。

也就是說,如果你有更復雜的邏輯,你應該創建一個輔助方法。 ERB模板不適合複雜的邏輯。這上面接近可接受。

+0

效果很好。但遺憾的是我遺漏了'link_to'標籤。想要修改你的答案?謝謝。 – Victor

+0

@Victor我編輯了我的答案。但下一次,你應該把你的整個問題都置於這個問題上。 –

+0

感謝您的更新。對不起,麻煩您了。再次感謝。 – Victor

相關問題