jkwantum
jkwantum

Reputation: 47

Best Practices for Styling ERB

I'd like to get some community input on best practices for styling your ERB templates.

I indent all my HTML tags in addition to Ruby code inside my ERB templates.

This usually makes for very readable ERB.

Assuming the above or similar parameters, how do you prefer indent longer lines?

Consider this example:

<div class="content">
  <div class="row">
    <div class="span10">
      <%= simple_form_for(@user, html: { class: 'form-horizontal' }) do |f| %>
        <%= f.input :MembershipID, label: 'Membership ID :', hint: 'Use the user\'s official Membership ID if they have one. Otherwise, enter their phone number (e.g. 2125551234)', input_html: { value: @user[:MembershipID] } %>
      <% end %>
    </div>
  </div>
</div>

The f.input line gets to be pretty ugly and unreadable.

I was thinking something like this would be ideal, but I wanted to get some feedback before changing a lot of my style.

<div class="content">
  <div class="row">
    <div class="span10">
      <%= simple_form_for(@user, html: { class: 'form-horizontal' }) do |f| %>
        <%= f.input :MembershipID, 
                label: 'Membership ID :', 
                hint: 'Use the user\'s official Membership ID if they have one. Otherwise, enter their phone number (e.g. 2125551234)', 
                input_html: { value: @user[:MembershipID] } %>
      <% end %>
    </div>
  </div>
</div>

I'm back and forth on whether double indenting from the ERB begin tag <%= or from the helper name f.input is better.

Please weigh in! (and please let's not turn this into a ERB vs HAML debate, assume ERB only!)

Thanks.

Upvotes: 4

Views: 4313

Answers (2)

Irongaze.com
Irongaze.com

Reputation: 1646

For long or complex ERB expansions, I often go multiline like so:

<div>
  <div>
    <%=
      some_call_with_lots_of_args_or_a_block(
        arg1,
        arg2
      ) do
        block_stuff()
      end
    %>
  </div>
</div>

Lots of lines, but the indents now all "make sense" for a given value of "sense". HTH!

Upvotes: 4

JeanMertz
JeanMertz

Reputation: 2270

Some things to consider:

  • Don't use "span10" and "row" classes, but instead apply this in your CSS
  • Use helpers, even if you don't plan on reusing them (at the moment), it cleans up your code

This gives you something like:

<div class="content">
  <%= simple_form_for(@user) do |f| %>
    <%= membership_input_field %>
  <% end %>
</div>

SCSS:

.content {
  @extend .row;
  #users_form {
    @extend .span10;
    @extend .form-horizontal;
  }
}

I can't test this right now, but you should get the general idea. Much cleaner, and much less useless classes to style your HTML.

Upvotes: 5

Related Questions