In every for loop in my application I do something like this
<% odd_or_even = 0
for event in @events
odd_or_even = 1 - odd_or_even
%>
I know there are some ways around to that by having automatic javascript
and
other solutions. But we support a large number of browsers and can’t be
sure
everyone has the latest browser so we have settled with this solution.
I was wondering if there is a way for me to open the for loop
functionaliyty and add this feature
- Every time the for loop starts initialize odd_or_even to zero.
- Change the value everytime the loop is executed.
- Make this varialbe odd_or_even visible exactly the way event is
visible.
Any suggestions.
Thanks
-=-
everyone has the latest browser so we have settled with this solution.
I was wondering if there is a way for me to open the for loop
functionaliyty and add this feature
- Every time the for loop starts initialize odd_or_even to zero.
- Change the value everytime the loop is executed.
- Make this varialbe odd_or_even visible exactly the way event is visible.
cycle() might be what you’re looking for…
<%- for item in @items do -%>
<tr class=“<%= cycle(“even”, “odd”) %>”>
… use item …
<%- end -%>
Not sure if this applies to your problem, but have you looked at cycle
()? I use it to alternate row colors in tables:
<% [1,2,3,4].each do |a| %>
<% CSSclassName = cycle(“even”, “odd”) %>
<%= a %> |
-Jason
–
Jason F. - jfrankov at pobox dot com
main 310-601-8454
cell 415-254-4890
Not entirely clear on what you’re looking for, so I’m not sure if this
will work for you, but I use odd? to generate alternating rows:
<% @records.each_with_index do |record, i| %>
<%=h record.field_1 %> |
etc. |
<% end %>
Thanks.
Both the suggestions are neat.
-=-
I think I just figured out a more elegant way of doing this.
class Array
def each_with_index_parity
self.each_with_index do |entry, index|
yield(entry, index, index % 2 == 0 ? 0 : 1)
end
end
end
This lets you write:
<% @records.each_with_index_parity do |record, i, parity| %>
<%=h record.field_1 %> |
etc. |
<% end %>
Or, if you prefer, you could put the class names right in the iterator:
class Array
def each_with_index_parity
self.each_with_index do |entry, index|
yield(entry, index, index % 2 == 0 ? ‘even’ : ‘odd’)
end
end
end
Which gives you:
<% @records.each_with_index_parity do |record, i, parity| %>
<%=h record.field_1 %> |
etc. |
<% end %>
Just a matter of taste, I guess.