简体   繁体   English

Ruby on Rails - 通过遍历实例变量在 html.erb 表中创建行

[英]Ruby on Rails - Creating rows in an html.erb table by looping over instance variable

I have an instance variable @referrals which contains names of referrals a person has done.我有一个实例变量@referrals,其中包含一个人所做的推荐名称。 I now need to create a table showing all these referrals as rows.我现在需要创建一个表格,将所有这些推荐显示为行。 I have tried the following code in the html.erb file:我在 html.erb 文件中尝试了以下代码:

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
      <th> Referral Emails </th>
      <% @referrals.each do |referrals| %>
        <tr> referrals </tr>
     <%end %>
</table>

and

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
      <th> Referral Emails </th>
      <% @referrals.each do |referrals| %>
        <%= <tr> referrals </tr> %>
     <%end %>
</table>

Both show up errors.两者都显示错误。

I am new with Ruby, help with the correct Ruby code is much appreciated.我是 Ruby 的新手,非常感谢您提供正确的 Ruby 代码帮助。 Thanks a ton in advance.提前致谢。

Edits: Code changes as suggested by @mu is too short.编辑:@mu 建议的代码更改太短。

By default in ERB, code blocks are enclosed in <% and %> delimiters, and if you want the result of the code block run, you use the = symbol inside, like <%= 'Hel' + 'lo' %>, world would output "Hello, world".在ERB中默认情况下,代码块是用<%%>分隔符括起来的,如果你想要代码块运行的结果,你可以在里面使用=符号,比如<%= 'Hel' + 'lo' %>, world将 output “你好,世界”。

Each member being iterated over with .each is named between the pipe symbols, so that is what you reference inside the block.使用.each迭代的每个成员都在 pipe 符号之间命名,因此这就是您在块内引用的内容。

Also table rows need to have table data, or <td> tags within the row <tr> tags.表格行也需要有表格数据,或者行<tr>标签中的<td>标签。

Here's what should work for you assuming that @referrals is a list of strings:假设@referrals是一个字符串列表,这对你有用:

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
  <tr> <th> Referral Emails </th> </tr>
  <% @referrals.each do |referral| %>
    <tr> <td> <%= referral %> </td> </tr>
  <% end %>
</table>

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

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