Be Genius

me

Bo Jeanes

I am an software engineer who has lived and worked in New York, Brisbane, Chicago, San Francisco, and now Melbourne. I primarily work in Ruby though am a functional programmer at heart and a fan of programming languages in general. In particular, I love Rust and Clojure but keep my eye on many langauges all the time.

Using partial layouts to DRY out your views

The other day we got some HTML from the designer of one of our clients to implement as the new UI for an app we are building at Mocra. Overall the HTML was good but implementing it started to feel a little moist (i.e. not DRY).

For example, around all the apps form the client’s design had a rounded white box, the HTML of which went something like this:

<div class="content-wht">
    <div class="content-wht-inside">
        <fieldset>
            <div class="frow">
                <label>Currency:</label>
                <select class="fs"><option>EUR</option></select>
            </div>

            <div class="frow frlast">
                <label>File:</label>
                <input type="file" name="" />
            </div>
        </fieldset>
    </div>
</div>

<div class="cround" align="center">
    <img src="/images/round-corners-bottom.gif" alt="" />
</div>

It’s a lot of div tags to have to repeat around every form that has this style. Luckily a nice feature of Rails partials can help out. Create a shared partial file that will act as a layout like this:

<!-- app/views/shared/_fieldset.html.erb -->
<div class="content-wht">
    <div class="content-wht-inside">
        <fieldset>
            <%= yield %>
        </fieldset>
    </div>
</div>

<div class="cround" align="center">
    <img src="/images/round-corners-bottom.gif" alt="" />
</div>

Then in your views that need to have this white box, simply wrap your content in that layout like so:

<% render :layout => 'shared/fieldset' do %>
  <div class="frow">
      <label>Currency:</label>
      <select class="fs"><option>EUR</option></select>
  </div>

  <div class="frow frlast">
      <label>File:</label>
      <input type="file" name="" />
  </div>
<% end %>

<!-- Or, if the inner content is already in a partial -->

<%= render, :partial => 'form', :layout => 'shared/fieldset' %>

Comments

None yet

You need to login with GitHub in order to comment.