Conditional tag wrapping in Rails / ERB

Joseph Ravenwolfe picture Joseph Ravenwolfe · Apr 27, 2011 · Viewed 25.3k times · Source

What would be the most readable and/or concise way to write this in ERB? Writing my own method isn't preferable, as I would like to spread a cleaner solution for this to others in my company.

<% @items.each do |item| %>
  <% if item.isolated? %>
    <div class="isolated">
  <% end %>

    <%= item.name.pluralize %> <%# you can't win with indentation %>

  <% if item.isolated? %>
    </div>
  <% end %>
<% end %>

== Update ==

I used a more generic version of Gal's answer that is tag agnostic.

def conditional_wrapper(condition=true, options={}, &block)
  options[:tag] ||= :div  
  if condition == true
    concat content_tag(options[:tag], capture(&block), options.delete_if{|k,v| k == :tag})
  else
    concat capture(&block)
  end
end

== Usage

<% @items.each do |item| %>
  <% conditional_wrapper(item.isolated?, :class => "isolated") do %>
    <%= item.name.pluralize %>
  <% end %>
<% end %>

Answer

Gal picture Gal · Apr 27, 2011

If you really want the DIV to be conditional, you could do something like this:

put this in application_helper.rb

  def conditional_div(options={}, &block)
    if options.delete(:show_div)
      concat content_tag(:div, capture(&block), options)
    else
      concat capture(&block)
    end
  end

which then you can use like this in your view:

<% @items.each do |item| %>
  <% conditional_div(:show_div => item.isolated?, :class => 'isolated') do %>
    <%= item.name.pluralize %>
  <% end %>
<% end %>