【问题标题】:Rails 4: Render partial with variableRails 4:使用变量渲染部分
【发布时间】:2016-04-23 00:57:27
【问题描述】:

我有以下部分:

<tr class="profile-row">
    <td class="profile-header"><%= attribute %></td>
    <% for week in @weeks %>
    <td><%= week.<%= field %> %></td> <!-- where it fails -->
    <% end %>
</tr>

...我希望能够提供 2 个变量,attributefield。当我尝试使用以下内容渲染部分时:

<%= 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... 而失败。我知道这不是提供变量的正确方法,但我应该怎么做呢?

【问题讨论】:

    标签: ruby-on-rails partial-views partials


    【解决方案1】:

    你不能像这样嵌套 ERB 标签:

    <%= week.<%= field %> %>
    

    改为这样做:

    <%= week %>.<%= field %>
    

    无论您在 ERB 标记中放置什么,都是 Ruby。所以你的代码是说“运行 Ruby 代码week.&lt;%= field 并将结果粘贴在这里。”但这不是有效的 Ruby 语法。

    或者如果field 包含属性的名称,你可以这样做:

    <%= week.send field.to_sym %>
    

    【讨论】:

      【解决方案2】:

      您不能嵌套 erb 标签。 如果您的变量是字符串,您可以将它们连接起来。

      <%= week + "." + field%>
      

      如果抛出错误,试试这个

      <%= week.to_s + "." + field.to_s%>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        • 2017-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多