ruby-on-rails – 嵌套haml循环以使“Collapse bootstrap-collapse.js”在Rails视图中正常工作

具有以下rails视图(haml):

.row
  .span7
    %h1 Listing categories
    %p
      - @categories.each do |category|
        .accordion-group
          .accordion-heading
            .accordion-toggle{"data-toggle" => "collapse", "data-target" => "##{category.path}"}= link_to category.name, "##{category.path}"
      - @competitors.each do |category_path, competitors|
        .accordion-body.table.collapse.in{:id => "#{category_path}"}
          %table.accordion-inner
            %thead
              %tr
                %th= "Project"
                %th= "Description"
                %th= "Watchers"
                %th= "Forks"
            %tbody
              - competitors.each do |competitor|
                %tr
                  %td
                    = link_to "#{competitor["html_url"]}".sub( "https:\/\/github.com\/", "" ), "#{competitor["html_url"]}"
                  %td
                    %span »
                    = competitor["description"]
                  %td
                    %span.badge.badge-info= competitor["watchers"]
                  %td
                    %span.badge.badge-warning= competitor["forks"]

我需要css类.accordion-group,包含.accordion-heading(在@ categories.each循环中)和.accordion-body(在另一个循环中:@ compet.each循环).

注意两个.each ruby​​循环,在haml中处于相同的“节点级别”,而它们的css类.accordion-heading和.accordion-body必须是.accordion-group css类容器.

我需要的resoulting html如下:

<div class="accordion-group">
  <div class="accordion-heading">
  <div class="accordion-body in collapse" id="collapse_id">
</div>
<div class="accordion-group">
  <div class="accordion-heading">
  <div class="accordion-body in collapse" id="collapse_id">
</div>
<div class="accordion-group">
  <div class="accordion-heading">
  <div class="accordion-body in collapse" id="collapse_id">
</div>
...

…虽然我目前得到这个错误的HTML代码:

<div class="accordion-group">
  <div class="accordion-heading">
</div>
<div class="accordion-group">
  <div class="accordion-heading">
</div>
<div class="accordion-group">
  <div class="accordion-heading">
</div>
...
<div class="accordion-body in collapse" id="collapse_id">
<div class="accordion-body in collapse" id="collapse_id">
<div class="accordion-body in collapse" id="collapse_id">
...

我无法找到缩进haml的正确方法……

最佳答案 在Haml中执行此类操作的方法是首先将数据转换为正确的格式,以使其与页面上的数据结构相匹配.然后迭代这个结构,标记应该更容易创建和更清晰.

例如,在这种情况下,您希望依次迭代元素对,每个元素一个,而不是单独遍历每个数组.然后你可以做这样的事情,(其中each_pair不是一个真正的方法,它仅用于演示):

- each_pair do |category, competitors|
  .accordion-group
    .accordion-heading
      ...
    .accordion-body
      ...

在Ruby中,你可以组合数组来获得与zip method对(或三元组或更大),所以你想要的是这样的:

- @categories.zip(@competitors) do |category, (category_path, competitors)|
  .accordion-group
    ...etc...

在这种情况下,@ competitors已经是一个数组数组,因此我们对其进行解构以获得我们想要的参数.

点赞