简体   繁体   English

Rails / ERB 中的条件标签包装

[英]Conditional tag wrapping in Rails / ERB

What would be the most readable and/or concise way to write this in ERB?在 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.我使用了标签不可知论的 Gal 答案的更通用版本。

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:如果你真的希望 DIV 是有条件的,你可以这样做:

put this in application_helper.rb把它放在 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.尽可能避免在视图中使用条件、if 等。

I like PreciousBodilyFluids' answer, but it doesn't strictly do exactly what your existing method does.我喜欢 PreciousBodilyFluids 的回答,但它并没有严格按照您现有的方法做。 If you really cannot have a wrapping div, this may be prefereable:如果你真的不能有一个包装 div,这可能是更可取的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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