I have this code view that is very hard to read and needs some 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">‹</a>
<a class="carousel-control right" href="<%= "#carousel_"+"p"+pi.to_s+"a"+i.to_s %>" data-slide="next">›</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>
Basically it lists each post, and renders each image of the post. Each image is a clickable thumbnail that pops up a modal conatining a carousel. Each carousel contains again each photo for the given post.
My idea was to move code from line 8 to line 24 and move it into a partial. The problem is that I get this error:
undefined local variable or method `pi' for #<#<Class:0x000000023b18f0>:0x007f91ec67c458>
Is there a way to make a partial inherit a variable from the parent?
You can pass local variable to the partial view:
here on the Guides of RubyOnRails, section 3.4.4 ‘Passing local variables’
their example :
In your case :
Hope this helps!