![](/img/trans.png)
[英]Rails - Outputting a list of items with a comma after each record excluding the last
[英]Dont have a comma on the last iteration of an each loop in Rails
我想在Rails中打印出逗號分隔的鏈接列表。
繼承人我得到了什么:
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
,
<% end %>
繼承人我想要的:
<a href="thing_a">Thing A</a>,
<a href="thing_b">Thing B</a>,
<a href="thing_c">Thing C</a>
但是現在我在循環的最后一次迭代中得到一個額外的逗號! 我該怎么辦?
一種方法是使用map
然后使用Array#join
:
<%= topics.map { |topic| link_to(topic.name, topic.link) }.join(',').html_safe %>
如果您想對代碼進行盡可能少的更改,可以使用以下內容
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
<% if(topic != topics.last) %>
,
<% end %>
<% end %>
如何使用each_with_index
,並且只在內容之前放置逗號,除非它不是第一個項目。
<% topics.each_with_index do |topic, i| %>
<% if i > 0 %>
,
<% end %>
<a href="<%= topic.link %>"><%= topic.name %></a>
<% end %>
我使用concat
helper在一行調用(用於活動記錄集合)中創建它:
<% concat (',') if e.bills.last != b %>
concat
是一個ERB助手(TextHelper),用於添加一些沒有<%= %>
語法的HTML,有助於添加幾個字符。
以下是完整的代碼:
<% event.bills.each do |b| %>
<%= link_to(b.number.to_s, bill_display_path(b)) %>
<% concat (',') if e.bills.last != b %>
<% end %>
您可以執行以下操作以打印除最后一項之外的所有項目的逗號:
<% topics.each do |topic| %>
<%= topic %>
<%= "," if topic != topics.last %>
<% end %>
這將檢查循環中的當前項是否是最后一項,並將使用<%= %>
語法輸出逗號。
試試吧。 這個對我有用
<%= topics.map{|p| p.topic.name}.join(",") %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.