简体   繁体   English

在Rails erb中使用变量

[英]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. 我来自.net c#剃须刀背景,所以我想知道如何在rails .erb视图中执行以下操作。

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? Rails erb文件是否可以执行此操作? 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 文档几乎回答了这个问题: 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: 要回答您的特定但非规范的Ruby问题,请确保:

<% 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.) (如果您要基于零或一的索引,我不太清楚;请根据需要调整所有示例。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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