views:

324

answers:

2

Hey,

I have a ajax method that renderes a @collection of users. This code is from the users partial. Now what I need to do is wrap a ul tag around the 3 li tags for every third object. How do I do this with HAML? I can't just add the %ul tag to "when 1" - because HAML closes the tag when that object has been rendered.

-case user_counter + 1
-when 1
  %li.first
    @user.login
-when 2
  %li
    @uer.login
-when 3
  %li.last
    @user.login

This is the result I am looking for:

<ul>
  <li>user1</li>
  <li>user2</li>
  <li>user3</li>
</ul>

<ul>
  <li>user4</li>
  <li>user5</li>
  <li>user6</li>
</ul>

etc.

+5  A: 

I think you want each_slice. It splits an Enumerable into groups of a specified size. You could do something like:

- @collection.each_slice(3) do |slice|
  %ul
    %li.first= slice[0].login
    %li= slice[1].login
    %li.last= slice[2].login
Chuck
Thank you :) This was just was I was looking for.
atmorell
What if I want to use the same code (%p login...etc) on each li tag, and only change the class? The actual content has a about 5 lines of items, and it does not seem right to paste the same content into each %li tag :/
atmorell
Looks like that's exactly what Sam's example does. Thanks.
atmorell
+2  A: 

This should be functionally equivalent to Chuck's answer, just a tad shorter.

I prefer the simplicity in Chuck's answer, but this does work as well.

- @collection.each_slice(3) do |slice|
  %ul
    - slice.zip([:first,nil,:last]).each do |user, klass|
      %li{:class => klass}= user.login
Sam Saffron
With so few items, besides being harder to read, it's actually longer in char count — they're just horizontal rather than vertical. But this general technique could be useful if the CSS ordering scheme was really complicated for some reason, because then you could have the array of users and an array of classes to use for difference item numbers.
Chuck
Agree, this answer is here mainly for a reference, I do not intend for it to be marked correct. For good measure I community wikid it.
Sam Saffron
Nice thing about this example is that you can use the same codeblock under %li, and only the class is looped. Thank you.
atmorell