浏览 1340 次
|
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
时间:2007-07-03 关键字: Rails ActionView capture_helper 源码
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 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |



