If else statements in .html.erb in views

dsp_099 picture dsp_099 · Jul 22, 2013 · Viewed 88.5k times · Source

In rails, I often run into the situation where inside the views I'll do something like

<% if @some_condition_previusly_established_in_a_controller %>
 <div class="one">123</div>
<% else %>
 <div class="two">something else</div>
<% end %>

It looks a bit cluttery. Is this an acceptable way of working with views or not?

Answer

tadman picture tadman · Jul 22, 2013

Unless you can think of a way to re-write this as a helper method, you're basically stuck with it looking kind of ugly. That's just how ERB is, as it was intended to be a minimal way of injecting Ruby into an otherwise plain-text template, not as something necessarily streamlined or elegant.

The good news is a syntax-highlighting editor will usually make your <% ... %> ERB blocks look visually different from your HTML so that can dramatically improve readability.

It's also why other representations like HAML have been created where that syntax is a lot less cluttered:

- if some_condition_previusly_established_in_a_controller
  .one 123
- else
  .two something else