Best practices on writing conditions in HTML tags?

html, ruby-on-rails

Solution

You're correct in assuming there is a nicer way. Putting conditional logic into views is against the spirit of MVC. Based on your examples you would be fine to use a simple helper method rather than any of the more complicated implementations that you might read about around the web.

You could create a helper method that looks something like this

def conditional_div(condition, true_class, false_class)
  content_tag :div, class: (condition ? true_class : false_class) do
    yield if block_given?
  end
end

Then in your view you can use the new helper like this

<%= conditional_div(c, 'my_class', '') do %>
  <p>Your content</p>
<% end %>

Problem

The question has surely already be asked, but I didn't find it. I am often forced to write code like that in views: - `<div class="<%= c ? 'my_class' : 'my_other_class' %>">` - `<div class="<%= 'my class' if c %>">` - `<div<%= c ? 'class="my_class"' : 'id="my_div"' %>>` Or (the prettier way, but the less readable) : ``` <% div_inner = capture do %> ... <% end %> <% if c %> <div class="my_class"><%= div_inner %></div> <% else %> <div><%= div_inner %></div> <% end %> ``` A last one : ``` <% div_inner = capture do %> ... <% end %> <%= content_tag(:div, div_inner, (c ? { :class => "my_class" } : {})) %> ``` I found all this solutions syntactically dirty. I am convinced that there is a nicer way. But witch ? Your own experiences are welcome.

Original source