23

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 %>

3 Answers 3

21

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 %>
1
  • Thought I wanted to avoid this. It is ultimately the direction I chose. Apr 27, 2011 at 21:25
7

Try:

<% @items.each do |item| %>
  <div class="<%= item.isolated? 'isolated' : '' %>">
    <%= item.name.pluralize %>
  </div>
<% end %>
2
  • Thanks but unfortunately this will not work because it will still include a div that will still break the flow. Apr 27, 2011 at 20:27
  • 1
    Worked for my purposes (outside the scope of this question). Thanks! Oct 30, 2013 at 17:39
1

I like PreciousBodilyFluids' answer, but it doesn't strictly do exactly what your existing method does. If you really cannot have a wrapping div, this may be prefereable:

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

A helper method to do all of this would probably look like this:

def pluralized_name_for(item)
  if item.isolated?
    content_tag(:div, item.name.pluralize, :class => 'isolated')
  else
    item.name.pluralize
  end
end

Then your view code would look like this:

<% @items.each do |item| %>
  <%= pluralized_name_for(item) %>
<% end %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.