使用渲染集合渲染树

时间:2011-06-14 05:00:41

标签: ruby-on-rails collections recursion partial

我有一个评论网站。显示它们时,不应缩进项目的第一次审核,但后续的审核应该是。

HTML输出应该类似于:

<ul>
  <li>review for item 1</li>
  <li>
    review for item 2
    <ul>
      <li>2nd review  for item 2</li>
      <li>3rd review for item 2</li>
    </ul>
  </li>
</ul>

我得到的输出看起来像这样:

<ul>
  <li>review for item 1</li>
  <li>
    review for item 2
  </li> <!-- wrong -->
  <li>  <!-- wrong -->
    <ul>
      <li>2nd review  for item 2</li>
      <li>3rd review for item 2</li>
    </ul>
  </li>
</ul>

_reviews.html.erb

<%= render :partial => "review_item", :collection => @reviews, :locals => { :reviews_local => @reviews } %>

_review_item.html.erb

<% if review_item_counter == 0 %>
<ul>
<% end %>

    <li>
    <% if @current_reviewable != review_item.id %>
       <% @current_reviewable = review_item.id %>
           <%= review_item.body %>

    <% else %>

        <% reviews_local.slice!(review_item_counter, reviews_local.size) %>
        <%= render :partial => "review_item", :collection => reviews_local, :locals => { :reviews_local => reviews_local } %>

    <% end %>
    </li>

<% if review_item_counter == reviews_local.size - 1 %>
</ul>
<% end %>

1 个答案:

答案 0 :(得分:0)

我建议你看看Ryan Bates的screencast。它完全涵盖了主题。