Conditional tag wrapping in Rails / ERB

2019-03-09 19:29发布

问题:

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

回答1:

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


回答2:

Try:

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


回答3:

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

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



回答4:

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