Rails / ERB中的条件标签包装 [英] Conditional tag wrapping in Rails / ERB

查看:59
本文介绍了Rails / ERB中的条件标签包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

==更新==

I

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

==用法

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


推荐答案

如果您真的希望DIV是有条件的,则可以做这样的事情:

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

将其放入application_helper.rb

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

这篇关于Rails / ERB中的条件标签包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆