Question

I am teaching myself HAML, and I'm trying to create a simple pattern of sorts. This is the HTML output I want:

<p>1 - a</p>
<p>2 - b</p>
<p>3 - a</p>
<p>4 - b</p>

As you can see, it counts up normally, and then adds either "a" or "b". I know you can do loops, and output the integer – but I can't figure out how to do the extra a/b logic for every second item.

- (1..4).each do |i|
  %p #{i} a

What's the best/easiest method to produce the exact markup from above? Is there an odd/even or modulus mechanism? What if the model changes slightly (e.g. more iterations, now it needs a/b/c)?

I know this can be solved with Javascript or even CSS, but I am looking for a solution with HAML only – I will however also accept solutions using Slim or Jade.

Was it helpful?

Solution

As you're using ruby to make the iteration I assume It's ok if you use some additional ruby code to make it work, so just put some simple code to solve this and output it with a "=". I think this is the easiest way to do it:

- (1..4).each do |i|
   %p= i.to_s + (i.even? ? " - b" : " - a")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top