Conditional Nesting in HAML?

1,399 views
Skip to first unread message

Cataclyst

unread,
Jun 29, 2009, 9:33:53 AM6/29/09
to Haml
Hi all,

so far I've been using haml with joy, but now I'm having a problem I'm
not able to solve: I want to nest content within a div, but only if a
specific local variable is true. The idea is to render a partial with
or without the surrounding "container" div just as needed, in order to
render a new item block or just replace the content within it (as an
AJAX response).

In ERB, I would do something similar to the following:

######

<% if !skip_outer -%>
<div id="some_id">
<% end -%>

<!-- some content here -->

<% if !skip_outer -%>
</div>
<% end -%>

#######

How do I accomplish the same thing with HAML? If-then statements don't
really work:

- if !skip_outer
#some_id
/ content here would be rendered only on !skip_outer, and even not
within the div#some_id

neither does it with an else case:

- if !skip_outer
#some_id
- else
/ content here would be rendered only on skip_outer

Any ideas to get something like that work "gracefully", i.e. without
having to double the content in both if-else-branches?

Thanks in advance.
André

scottwb

unread,
Jun 29, 2009, 12:50:14 PM6/29/09
to Haml
Try something like this...define a helper like:

def conditional_div(condition, attributes, &block)
if condition
haml_tag :div, attributes, &block
else
haml_concat capture_haml(&block)
end
end

Then, in your template do:

- conditional_div(!skip_outer, {:id => "some_id"}) do
/ some content here

Cataclyst

unread,
Jun 29, 2009, 2:28:48 PM6/29/09
to Haml
That's it, the helper method works great. :) Thanks a lot, Scott.

André

Nathan Weizenbaum

unread,
Jun 29, 2009, 10:31:34 PM6/29/09
to ha...@googlegroups.com
Or more directly,

def haml_tag_if(condition, *args, &block)
  if condition
    haml_tag *args, &block
  else
    yield
  end
end

That might be something worth adding to Haml::Helpers. Thoughts?

Noel

unread,
Jun 30, 2009, 9:05:38 PM6/30/09
to ha...@googlegroups.com
I have a somewhat related question

Could I use this technique to conditionally nest some content? I'm
sorry if this is obvious from the last response, but I didn't get it
yet.

I want to render some columns and in the controller I determine how
many items should be in each column.

the markup I am trying to get is someting like

%div#col_0
ul.group
li.item
li.item
li.item
ul.group
li.item
li.item
%div#col_1
ul.group
li.item
ul.group
li.item
li.item

from index.html.haml I am calling render :partial on group and from
that partial I render :partial item

So I need to be able to conditionally start / end the column div in
the group partial.

How should I go about this?

Thanks,
Noel

Nathan Weizenbaum

unread,
Jul 1, 2009, 12:11:56 AM7/1/09
to ha...@googlegroups.com
I'd use a helper that takes the array of items and divides it up into sub-arrays of the desired length (maybe use Array#each_slice).
Reply all
Reply to author
Forward
0 new messages