重构视图(和继承的变量)

时间:2012-09-28 16:30:54

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

我有这个代码视图很难阅读,需要一些重构:

  <div class="tab-content">
    <% @posts.each_with_index do |post,pi| %>
      <div class="tab-pane fade <%= 'active in' if pi == 0 %>" id="<%= "post_"+ pi.to_s %>">
        <h2><%= post.title %></h2>
        <ul class="thumbnails">
          <% post.assets.each_with_index do |asset, i| %>
            <%= link_to (image_tag (asset.photo.url(:thumb))), "#p"+pi.to_s+"a"+i.to_s, :"data-toggle" => "modal", :class => "thumbnail span2" %>
            <div class="modal hide fade" id="<%= "p"+pi.to_s+"a"+i.to_s %>" >
              <div class="modal-body">
                <div class="carousel slide" id="<%= "carousel_"+"p"+pi.to_s+"a"+i.to_s %>" >
                  <div class="carousel-inner" >
                    <% post.assets.each_with_index do |photo, ai| %>
                      <div class="<%= 'active ' if ai == i %>item">
                        <%= image_tag photo.photo.url(:normal) %>
                        <div class="carousel-caption">
                          <h4><%= post.title %></h4>
                        </div>
                      </div>
                    <% end %>
                  </div>
                  <a class="carousel-control left" href="<%= "#carousel_"+"p"+pi.to_s+"a"+i.to_s %>" data-slide="prev">&lsaquo;</a>
                  <a class="carousel-control right" href="<%= "#carousel_"+"p"+pi.to_s+"a"+i.to_s %>" data-slide="next">&rsaquo;</a>
                </div>
              </div>
            </div>
          <% end %>
        </ul>
        <div><%= mdown(post.content) %></div>
        <p><%= raw post.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %></p>
        <p>
          <%= link_to 'Show', post %>
          <%= link_to 'Edit', edit_post_path(post) %>
          <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
        </p>
      </div>
    <% end %>

    <br />

    <%= link_to 'New Post', new_post_path %>
  </div>

基本上它列出了每个帖子,并呈现帖子的每个图像。每个图像都是一个可点击的缩略图,弹出一个包含旋转木马的模态。每个轮播再次包含给定帖子的每张照片。

我的想法是将代码从第8行移到第24行并将其移动到部分代码中。问题是我收到了这个错误:

undefined local variable or method `pi' for #<#<Class:0x000000023b18f0>:0x007f91ec67c458>

有没有办法从父级部分继承变量?

2 个答案:

答案 0 :(得分:3)

您可以将局部变量传递给局部视图: here on the Guides of RubyOnRails, section 3.4.4 'Passing local variables'

他们的例子:

<%= render :partial => "form", :locals => { :zone => @zone } %>

在你的情况下:

<%= render :partial => "modal_box", :locals => { :pi => pi } %>

希望这有帮助!

答案 1 :(得分:1)

将当地人传递给部分......

<%= render :partial => 'blah' , :locals => { :var => value} %>

<%= render 'blah' , :var => value %>