Let's say I have 16 results
On every 4th item I need to add a class "no-margin" (because every item on the left needs a margin right to create spacing but the last one doing that would break the layout, thus the need for this).
开发者_JAVA百科What's the best way to do this?
I have it very rails-like right now.
render :partial => @collection
_collection.html.haml
stuff
Is there something that I can put in the partial that would solve this or would it have to happen outside?
Thanks.
When you render a collection, Rails creates an hidden index. In this case, you can combine the module with the index to obtain the result.
# _partial.html.erb
<div class="<% if (partial_counter % 4) == 0 %>no-margin<% end %>">
...
</div>
# action
<%= render => "partial", :collection => @collection %>
Even better, extract the logic into a Helper method.
Note. The name of the counter is <partial_name>_counter
.
You might be able to use cycle() to do this: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001753
Not sure whether it would look different in haml, but in an erb template, I would do this:
<% @collection.each do |item| %>
<tr class="<%= cycle('yes-margin', 'yes-margin', 'yes-margin', 'no-margin' %>">
...
</tr>
<% end %>
I'd be inclined to use the each_with_index
method from enumerable
.
# app/views/questions/index.html.haml
- @questions.each_with_index do |question, index|
%li{ :class => no_margin(index) }
= render :partial => 'question', :object => question
Your helper might look like this.
# app/helpers/questions_helper.rb
def no_margin(index)
index % 4 == 0 ? 'no-margin' : 'margin'
end
精彩评论