如何在 <%= for %> 视图助手中增加 ID

How to increment ID inside a <%= for %> view helper

我的代码中有这个:

<%= for empresa <- @empresas do %>
    <%= render myProject.ComponentView, "smallPlacard.html",
        smallPlacard_id: "1",
        smallPlacard_class: "Company",
        smallPlacard_mainText: company.name
    %>
 <% end %>

我希望 smallPlacard_id 会针对每个呈现的元素自动递增。 Phoenix/functional 的最佳方式是什么?

您可以使用 Enum.with_index/2:

<%= for {empresa, id} <- Enum.with_index(@empresas) do %>
    <%= render myProject.ComponentView, "smallPlacard.html",
        smallPlacard_id: id + 1,
        smallPlacard_class: "Company",
        smallPlacard_mainText: company.name
    %>
 <% end %>

我在这个例子中增加了 1,因为索引是基于 0 的。如果您像以前一样需要字符串,请改用 "#{id + 1}"

很有魅力

 <%= for {item, id} <- Enum.with_index(@items) do %>
     <tr>
     <td><%= id + 1 %></td>
     </tr>
 <% end %>