Rails 4:使用变量渲染部分
Rails 4: Render partial with variable
我有以下部分:
<tr class="profile-row">
<td class="profile-header"><%= attribute %></td>
<% for week in @weeks %>
<td><%= week.<%= field %> %></td> <!-- where it fails -->
<% end %>
</tr>
...我希望能够提供 2 个变量,attribute
和 field
。当我尝试使用以下内容渲染局部时:
<%= render 'foo', attribute: 'Current Weight', field: 'current_weight' %>
...我要:
<tr class="profile-row">
<td class="profile-header">Current Weight</td>
<% for week in @weeks %>
<td><%= week.current_weight %></td> <!-- where it fails -->
<% end %>
</tr>
...但是 syntax error, unexpected tOP_ASGN...
失败了。我知道这不是提供变量的正确方法,但我应该怎么做呢?
您不能像这样嵌套 ERB 标签:
<%= week.<%= field %> %>
改为这样做:
<%= week %>.<%= field %>
无论您在 ERB 标签中放入什么,都是 Ruby。所以你的代码说 "Run the Ruby code week.<%= field
and stick the result here." 但那是无效的 Ruby 语法。
或者如果 field
包含属性名称,您可以这样做:
<%= week.send field.to_sym %>
不能嵌套 erb 标签。
如果您的变量是字符串,您可以连接它们。
<%= week + "." + field%>
如果抛出错误试试这个
<%= week.to_s + "." + field.to_s%>
我有以下部分:
<tr class="profile-row">
<td class="profile-header"><%= attribute %></td>
<% for week in @weeks %>
<td><%= week.<%= field %> %></td> <!-- where it fails -->
<% end %>
</tr>
...我希望能够提供 2 个变量,attribute
和 field
。当我尝试使用以下内容渲染局部时:
<%= render 'foo', attribute: 'Current Weight', field: 'current_weight' %>
...我要:
<tr class="profile-row">
<td class="profile-header">Current Weight</td>
<% for week in @weeks %>
<td><%= week.current_weight %></td> <!-- where it fails -->
<% end %>
</tr>
...但是 syntax error, unexpected tOP_ASGN...
失败了。我知道这不是提供变量的正确方法,但我应该怎么做呢?
您不能像这样嵌套 ERB 标签:
<%= week.<%= field %> %>
改为这样做:
<%= week %>.<%= field %>
无论您在 ERB 标签中放入什么,都是 Ruby。所以你的代码说 "Run the Ruby code week.<%= field
and stick the result here." 但那是无效的 Ruby 语法。
或者如果 field
包含属性名称,您可以这样做:
<%= week.send field.to_sym %>
不能嵌套 erb 标签。 如果您的变量是字符串,您可以连接它们。
<%= week + "." + field%>
如果抛出错误试试这个
<%= week.to_s + "." + field.to_s%>