conterio
conterio

Reputation: 1174

using variables in rails erb

I'm coming from a .net c# razor background, so I'm wondering how I might do the following in rails .erb view.

Razor:

@{var i = 0}
<table>
     <tr><th>name</th></tr>
     @foreach item in collection{
        <tr>
             <td>@i++.@item.name</td>
        </tr>
     }
</table>

I want a way to use an iteration variable in the view. Does a rails erb file have the ability to do this? where I can create the variable in the view and interact with it?

thanks in advance.

Upvotes: 3

Views: 10027

Answers (1)

Dave Newton
Dave Newton

Reputation: 160291

The docs pretty much answer this: https://apidock.com/ruby/ERB

Although I wouldn't do it like that, rather:

<table>
  <tr><th>name</th></tr>

  <% collection.each_with_index do |item, i| %>
    <tr>
      <td>
        <%= i %>. <%= item %>
      </td>
    </tr>
  <% end %>
</table>

To answer your specific but non-canonical-Ruby question, sure:

<% i = 0 %>
<table>
  <% collection.each do |item| %>
    <!-- Etc -->
    <%= i += 1 %>

(Not clear to me if you want zero- or one-based indexing; adjust all examples as required.)

Upvotes: 6

Related Questions