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

Pau*_*iro 3 elixir phoenix-framework

我的代码中有这个:

<%= for empresa <- @empresas do %>
    <%= render myProject.ComponentView, "smallPlacard.html",
        smallPlacard_id: "1",
        smallPlacard_class: "Company",
        smallPlacard_mainText: company.name
    %>
 <% end %>
Run Code Online (Sandbox Code Playgroud)

我希望smallPlacard_id每个渲染元素都会自动递增.在凤凰城/功能方式中做到这一点的最佳方式是什么?

Gaz*_*ler 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 %>
Run Code Online (Sandbox Code Playgroud)

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

  • `Enum.with_index`或者将'offset`作为第二个参数,所以你可以使用`Enum.with_index(@ empresas,1)`作为基于一的索引,并用`i`替换`i + 1`.如果您需要在多个位置使用索引,这将特别有用. (7认同)