DRYing html boxes

Creating html boxes can result in a lot of repetitive lines of code when you use a lot of them in your projects. Take this one for example. It is not so long... I can show you examples that are more messy but you don't want that, do you? :-)

1
2
3
4
5
6
7
<div class="box">
        <div class="r-tl"></div><div class="r-tr"></div>
        <div class="r-bl"></div><div class="r-br"></div>
        <div class="body">
            bla bla bla
        </div>
</div>

The only part that contains different html code in different boxes is inside div with class="body". So, we can create a helper method and call it with a block where we put that specific html code inside.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def box(style, &block)
   raise 'Block expected!' unless block_given?
   content = capture(&block)
                
   html = <<-EOF
   <div class="box" style="#{style}">
      <div class="r-tl"></div><div class="r-tr"></div>
      <div class="r-bl"></div><div class="r-br"></div>
      <div class="body">
            #{content}
      </div>
   </div>
   EOF
   concat(html, block.binding)
end
1
2
3
<% box('width: 500px;') do %>
   bla bla bla
<% end %>
Posted at 20PM on 11/09/07 | 0 comments | Filed Under: | read on

About

I am Anton Kuzmin. I am a web developer. I code mostly using ruby on rails.