简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM