Jason
Jason

Reputation: 881

How do I DRY up repeated nested HAML?

I am writing email views, which are particularly nasty in their use of nested tables. Each of the many sections of my email wants the same nasty cruft around it:

%table.centered
  %tbody
    %tr
      %td
        %table.one-col{"emb-background-style" => ""}
          %tbody
            %tr
              %td.column
                %div
                  .column-top  
                %table.contents
                  %tbody
                    %tr
                      %td.padded
                        COPY COPY COPY ETC.

The content of each section is lots of copy and links and whatnot, and putting that into ruby strings or rendering it from separate files would be hard to follow. It's the cruft I want to obscure, not the section content.

So, is there a way to somehow concatenate the cruft to make the HAML less indented and crufty?

Upvotes: 0

Views: 207

Answers (1)

MilesStanfield
MilesStanfield

Reputation: 4639

This IS possible to do without rendering partials.

You can make a helper method like this to hide all that 'cruft' as you put it.

# app/helpers/application_helper.rb
def nested_blk_call(&blk)
  content_tag :div, class: "nested-tag-level-1" do
    content_tag :div, class: "nested-tag-level-2" do
      content_tag :div, class: "nested-tag-level-3" do
        blk.call
        ""
      end
    end
  end
end

# some_view.html.haml
= nested_blk_call do
  .you-can-add-more-haml
    COPY COPY COPY ETC.

this would output in browser

<div class="nested-tag-level-1">
  <div class="nested-tag-level-2">
    <div class="nested-tag-level-3">
      <div class="you-can-add-more-haml">
        COPY COPY COPY ETC.
      </div>
    </div>
  </div>
</div>

Upvotes: 5

Related Questions