Recursive haml

40 views
Skip to first unread message

Bruce Perens

unread,
Aug 11, 2007, 11:42:07 AM8/11/07
to Haml
Hi,

In building hierarchical HTML structures, it's most elegant to use
recursive blocks of haml. Here is a demo recursive haml script:

%html
%body
- p = Proc.new do |data, block|
%ul
- data.each do |l|
%li
- if l.class == Array
- block.call(l, block)
- else
= l

- p.call([[1,2,3],[4,5,6],[7,8,9]], p)

This works, except for one little quibble: the HTML output isn't
indented properly. It renders just fine. What I'd like to know is:

How do I fix the indentation?
Is this the most elegant way to write recursive blocks in haml?

Thanks

Bruce

Nathan Weizenbaum

unread,
Aug 11, 2007, 2:50:00 PM8/11/07
to ha...@googlegroups.com
If you really need to manipulate tabulation, call the Haml #tab_up and
#tab_down functions, which increase and decrease tabulation,
respectively. That's not what I'd do in this case, though; I'd either
define the recursive block as a helper using #open (a Haml helper),
which should automatically indent correctly, or use #capture (a Rails
helper) to make the return value of the block a string which will be
automatically indented.

- Nathan

Hampton

unread,
Aug 13, 2007, 6:46:19 PM8/13/07
to ha...@googlegroups.com
Yeah, I'd definitely implement this using an awesome helper.

def nice_bit
Proc.new do |data, block|
open(:ul) do
data.each do |item|
open(:li, (item.class == Array ? block.call(item, block) : item))
end
end
end


p.call([[1,2,3],[4,5,6],[7,8,9]], p)

end

Something like that?
(untested code!)

-hampton.

Reply all
Reply to author
Forward
0 new messages