【问题标题】:Rails is there any other way of doing this loop? DRYRails 还有其他方法可以执行此循环吗?干燥
【发布时间】:2011-08-07 17:29:13
【问题描述】:

Rails 以保持干燥着称。

我要创建一个这样的表:http://www.duoh.com/csstutorials/tablesv2/

还有其他方法可以重复循环吗?

<tbody>
    <tr>
        <th class="column1" scope="row">Data usage</th>

<%= @something.each do |info| %>
        <td><%= info.name %></td>
<% end %>
    </tr>   
     <tr class="odd">
        <th class="column1" scope="row">Opslag Capaciteit</th>

<%= @something.each do |info| %>
<td><%= info.price %></td>
<% end %>
    </tr>   
    </tbody>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    使用 HAML 会导致很多问题:

    %tbody
      %tr
        %th.column1{:scope=>"row"} Data usage
        -@something.each do |info|
          %td= info.name
      %tr.odd
        %th.column1{:scope=>"row"} Opslag Capaciteit
        -@something.each do |info|
          %td= info.price
    

    对不起,如果下面的代码不起作用。很复杂,我没有测试过。

    如果你真的想让它更简单,那么你可以在ApplicationHelper(或此视图中可用的任何其他帮助模块)中放置一个辅助函数,如下所示:

    def my_row(name, &block)
      @row_count ||= -1
      @row_count += 1
      row_contents = content_tag(:th, name, :class=>'column1', :scope=>'row')
      @something.each do |item|
        row_contents += content_tag(:td, capture(item, &block))
      end
      content_tag(:tr, row_contents, :class => @row_count.even? ? 'even' : 'odd')
    end
    

    那么在你看来,就这样做:

    %tbody
      =my_row "Data Usage" do |item|
        =item.name
      =my_row "Opslag Capaciteit" do |item|
        =item.price
    

    或者在 ERB 中我认为是:

    <tbody>
      <%= my_row "Data Usage" do |item| %> <%= item.name %> <% end %>
      <%= my_row "Opslag Capaciteit" do |item| %> <%= item.price %> <% end %>
    </tbody>
    

    【讨论】:

      【解决方案2】:

      抽象功能正是 ruby​​ 的 block/yield 结构的目的。

      在助手中:

      def tds list
        list.map do |item|
          content_tag :td, yield(item)
        end.join("\n")
      end
      

      那么在你看来:

      <%= tds @something {|i| i.name } %>
      
      <!-- other stuff -->
      
      <%= tds @something {|i| i.price } %>
      

      【讨论】:

        猜你喜欢
        • 2016-12-23
        • 2023-03-30
        • 2020-10-19
        • 2012-01-29
        • 2010-12-21
        • 2014-09-17
        • 2011-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多