如何在<%= for%>内增加ID查看助手

时间:2016-03-25 17:46:39

标签: elixir phoenix-framework

我的代码中有这个:

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

我希望smallPlacard_id对于每个渲染元素自动递增。 以凤凰城/功能性方式做到这一点的最佳方式是什么?

2 个答案:

答案 0 :(得分:6)

您可以使用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}"

答案 1 :(得分:1)

就像一个魅力

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