Question

  • ruby 2.0.0p247
  • Rails 4.0.0

How to alternate the html content of my loop?

- @recipes.each do |recipe|
    = image_tag "path.png", :height => "?", :width => "?"

Fox example:

The output expected is like:

image_tag "medium-01.png", :height => "200", :width => "350"

image_tag "small-02.png", :height => "183", :width => "285"
image_tag "small03.png", :height => "183", :width => "285"
image_tag "small-04.png", :height => "183", :width => "285"
image_tag "small-05.png", :height => "183", :width => "285"

image_tag "medium-06.png", :height => "200", :width => "350"
image_tag "medium-07.png", :height => "200", :width => "350"

image_tag "small-08.png", :height => "183", :width => "285"
image_tag "small-09.png", :height => "183", :width => "285"

Result desired bellow:

enter image description here

In jquery I did this. Maybe helps:

$("div").each(function(i, element) {
    if (i % 5 == 0 || i % 6 == 0) {
        $(this).css({"background":"dark_gray_color"});
    }
    else {
        $(this).css({"background":"magenta_color"});
    }
});

Am I clear?

Was it helpful?

Solution

Use ruby's Enumerable#each_with_index to get a loop similar to the jquery one you posted.

@recipes.each_with_index do |recipe, i|
  if [0,5,6].include? i
    h, w = 200, 350
  else
    h, w = 183, 285
  end

  image_tag "path.png", :height => "#{h}", :width => "#{w}"
end

OTHER TIPS

This code should get the output you desire. Not sure I have HAML right(not tested).

- @recipes.each.with_index do |recipe, i|
  - if [i, i % 5, i % 6].any?(&:zero?)
      = image_tag "medium-#{'%02d' % (i + 1)}.png", :height => "200", :width => "350"
  - else
      = image_tag "small-#{'%02d' % (i + 1)}.png", :height => "183", :width => "285"
  - end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top