Paul A Jungwirth
Paul A Jungwirth

Reputation: 24541

Remove whitespace in Haml with a loop

This question is similar to this one, but with an extra wrinkle:

Auto-removing all newlines from Haml output

Suppose you're constructing a comma-separated list of links with code like this:

- foos.each_with_index do |foo, i|
  = ', ' if i > 0
  = link_to foo.name, foo

How do you do that without getting whitespace in front of the comma? I don't see any way to do this with the existing alligator operators or surround/precede/succeed.

Is there some way to rewrite the loop so you can use these operators?

Upvotes: 0

Views: 473

Answers (2)

Roi
Roi

Reputation: 1647

HAML comes with a succeed method which can be used here:

- foos.each do |foo|
  = succeed (foo == foos.last) ? '' : ', ' do
    = link_to foo.name, foo

Using string interpolation or an expression, you can conditionally show an empty string or a comma w/ a space.

Upvotes: 3

davidgoli
davidgoli

Reputation: 2495

Since link_to is just a helper that returns a string, you can do it in a single statement:

- foos.each_with_index do |foo, i|
    = link_to(foo.name, foo) + (i < foos.length ? ', ' : '')

However, you probably want to extract this code into a helper and write tests.

Upvotes: 1

Related Questions