原创作者: hideto   阅读:1048次   评论:0条   更新时间:2011-05-26    
Struts有Tiles,WebWork可以用sitemesh,而Rails呢?有Capture!
请看活生生的例子先:
例子1:
#  layout.rhtml:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>layout with js</title>
</head>
<body>
  <%= @greeting %>
</body>
</html>

#  view.rhtml:

<% @greeting = capture do %>
  Welcome To my shiny new web page!
<% end %>

使用capture方法可以extract任何东西到一个实例变量里(如@greeting),这样就可以在你的模板其他地方甚至layout中使用它了

例子2:
#  layout.rhtml:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>layout with js</title>
  <script type="text/javascript">
    <%= yield :script %>
  </script>
</head>
<body>
  <%= yield %>
</body>
</html>

#  view.rhtml:

<% content_for("script") do %>
  alert('hello world')
<% end %>

使用content_for方法也是封装一段html或者javascript或者什么东西,这样可以得到一个变量(如@content_for_script),我们可以在layout中
使用<%= yield :script %>或者<%= @content_for_script %>来使用

好了,看看代码capture_helper.rb:
module ActionView
  module Helpers
    module CaptureHelper

      def capture(*args, &block)
        begin
          buffer = eval("_erbout", block.binding)
        rescue
          buffer = nil
        end
        if buffer.nil?
          capture_block(*args, &block)
        else
          capture_erb_with_buffer(buffer, *args, &block)
        end
      end

      def content_for(name, content = nil, &block)
        eval "@content_for_#{name} = (@content_for_#{name} || '') + capture(&block)"
      end

      private
        def capture_block(*args, &block)
          block.call(*args)
        end
      
        def capture_erb(*args, &block)
          buffer = eval("_erbout", block.binding)
          capture_erb_with_buffer(buffer, *args, &block)
        end
      
        def capture_erb_with_buffer(buffer, *args, &block)
          pos = buffer.length
          block.call(*args)
          data = buffer[pos..-1]
          buffer[pos..-1] = ''
          data
        end
      
        def erb_content_for(name, &block)
          eval "@content_for_#{name} = (@content_for_#{name} || '') + capture_erb(&block)"
        end
      
        def block_content_for(name, &block)
          eval "@content_for_#{name} = (@content_for_#{name} || '') + capture_block(&block)"
        end
    end
  end
end

我们看到content_for实际上是对capture方法的封装,并生成一个以content_for开头的实例变量,而且content_for可以重复定义同一name,这样content会累加
相关文章不可小视的ERB和capture
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics