3

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>@[email protected]</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.

1
  • Even though this has a negative effort number, this question/answer really has helped me. I hope it helps others in the future :) Commented Apr 24, 2017 at 20:15

1 Answer 1

6

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. The .item was a typo, the item is the object i want to print out. and the period (.) is just for the number showing what row is on, kind of like an ordered list <ol>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.