[英]Refactoring a Rails view to be DRY
I'm not sure if the title is representative of my actual problem but as I'm relatively new to programming it's the best I could come up with. 我不确定标题是否代表我的实际问题,但是由于我相对较不熟悉编程,所以我想出的是最好的。 Let me know if you have something better?
让我知道您是否有更好的选择?
I want to refactor my current view to be both more manageable and in keeping with the DRY method. 我希望将当前视图重构为更易于管理,并与DRY方法保持一致。
My view: 我的观点:
<div class="row">
<div class="span8">
<% @photos.each_with_index do |photo, index| %>
<% if index == 0 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
<div class="span4">
<% @photos.each_with_index do |photo, index| %>
<% if index == 2 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
<div class="span4">
<% @photos.each_with_index do |photo, index| %>
<% if index == 3 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
</div><!--/.row -->
<div class="row">
<div class="span8 pull-right">
<% @photos.each_with_index do |photo, index| %>
<% if index == 4 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
<div class="span4">
<% @photos.each_with_index do |photo, index| %>
<% if index == 2 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
<div class="span4">
<% @photos.each_with_index do |photo, index| %>
<% if index == 3 %>
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
<% end %>
<% end %>
</div>
</div><!--/.row -->
My controller: 我的控制器:
def index
if params[:tag]
@photos = Photo.tagged_with(params[:tag])
else
@photos = Photo.order("created_at DESC")
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @photos }
end
end
If I just wanted to show a few photos this wouldn't be a problem. 如果我只想显示几张照片,那不是问题。 However, as this view is essentially a feed of every photo uploaded it becomes unmanageable very quickly.
但是,由于此视图本质上是上传的每张照片的提要,因此变得非常难以管理。 Especially when I have to reference say 100/1000/10,000 photos with their index.
特别是当我必须参考100/1000 / 10,000张照片及其索引时。 Is there a better way to refactor this view?
有没有更好的方法来重构这种观点? Keeping in mind the changing spans8, span4, span4 which are then reversed span4, span4, span8 and so on and so forth.
记住不断变化的span8,span4,span4,然后将它们颠倒为span4,span4,span8,依此类推。
Try this: 尝试这个:
<% @photos.each_with_index do |photo, index| %>
<div class="row">
<div class="span<%= cycle(8, 4, 4) %>">
<!-- <h1><%= photo.title %></h1> -->
<img src="<%= photo.image_url.to_s %>">
</div>
</div>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.