【问题标题】:Conditional tag wrapping in Rails / ERBRails / ERB 中的条件标签包装
【发布时间】:2011-08-14 04:09:45
【问题描述】:

在 ERB 中编写此代码最易读和/或最简洁的方式是什么?编写我自己的方法并不可取,因为我想将一个更清洁的解决方案传播给我公司的其他人。

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

== 更新 ==

我使用了一个更通用的 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

== 用法

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

【问题讨论】:

    标签: ruby-on-rails ruby erb


    【解决方案1】:

    如果你真的希望 DIV 是有条件的,你可以这样做:

    把它放在 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
    

    然后你可以在你的视图中这样使用它:

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

    【讨论】:

    • 我想避免这种情况。这是我最终选择的方向。
    【解决方案2】:

    试试:

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

    【讨论】:

    • 谢谢,但不幸的是这不起作用,因为它仍然包含一个仍然会中断流程的 div。
    • 为我的目的工作(超出了这个问题的范围)。谢谢!
    【解决方案3】:

    我喜欢 PreciousBodilyFluids 的回答,但它并没有严格按照您现有的方法做。如果你真的不能有一个包装 div,这可能是更可取的:

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

    执行所有这些操作的辅助方法可能如下所示:

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

    那么您的视图代码将如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      相关资源
      最近更新 更多