1
  • 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?

1
  • Couple of questions: Where are image names coming from? Where do the height and width values come from? How would you match the numeric index values to the correct path (for example, what happens if @recipes is in a different order, and you end up with small-01.png instead of medium-01.png..etc)? Commented Mar 3, 2014 at 22:50

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't know the "each_with_index". Works perfectly!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.