简体   繁体   中英

Conditional tag wrapping in Rails / ERB

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

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

Try:

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

I will suggest using a helper that will take care of your logic.

Avoid conditionals, if, etc in views as long as possible.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM