【问题标题】:Rails: What's the difference between capture and content_for?Rails:capture 和 content_for 有什么区别?
【发布时间】:2012-06-06 02:43:16
【问题描述】:

在 Rails 3.2 CaptureHelper 中,使用 capturecontent_for 有什么区别,我为什么要选择其中一个?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    如果您查看 content_for 源,它会在内部调用 capture:

    def content_for(name, content = nil, &block)
      if content || block_given?
        content = capture(&block) if block_given?
        @view_flow.append(name, content) if content
        nil
      else
        @view_flow.get(name)
      end
    end
    

    因此,通过阅读该方法,看起来 content_for 的主要优点是它可以多次调用相同命名内容的多个块,并且每个额外的调用只会附加到已经呈现的任何内容上。而在捕获的情况下,如果您调用:

    <% @greeting = capture do %>
      Hello
    <% end %>
    

    然后再调用:

    <% @greeting = capture do %>
      Or, in espanol, Hola
    <% end %>
    

    那么最后一部分是唯一会被捕获的部分,'Hello' 将被丢弃。然而,在 content_for 中执行类似的操作将导致第二个调用附加到“Hello”。

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 2011-12-12
      • 2010-09-16
      • 2012-03-14
      • 2012-02-06
      • 2011-02-25
      • 2011-11-22
      • 2015-03-26
      • 2013-08-19
      相关资源
      最近更新 更多