module Merb module ErubisCaptureMixin # Capture allows you to extract a part of the template into an # instance variable. You can use this instance variable anywhere # in your templates and even in your layout. # # Example of capture being used in a .herb page: # # <% @foo = capture do %> #
Some Foo content!
# <% end %> def capture(*args, &block) # execute the block begin buffer = eval("_buf", block.binding) rescue buffer = nil end if buffer.nil? capture_block(*args, &block) else capture_erb_with_buffer(buffer, *args, &block) end end # Calling throw_content stores the block of markup for later use. # Subsequently, you can make calls to it by name with catch_content # in another template or in the layout. # # Example: # # <% throw_content :header do %> # alert('hello world') # <% end %> # # You can use catch_content :header anywhere in your templates. # # <%= catch_content :header %> def throw_content(name, content = nil, &block) eval "@_#{name}_content = (@_#{name}_content || '') + capture(&block)" end # catch_content catches the thrown content from another template # So when you throw_content(:foo) {...} you can catch_content :foo # in another view or the layout. def catch_content(name) instance_variable_get("@_#{name}_content") end private def capture_block(*args, &block) block.call(*args) end def capture_erb(*args, &block) buffer = eval("_buf", block.binding) capture_erb_with_buffer(buffer, *args, &block) end def capture_erb_with_buffer(buffer, *args, &block) pos = buffer.length block.call(*args) # extract the block data = buffer[pos..-1] # replace it in the original with empty string buffer[pos..-1] = '' data end def erb_content_for(name, &block) eval "@_#{name}_content = (@_#{name}_content|| '') + capture_erb(&block)" end def block_content_for(name, &block) eval "@_#{name}_content = (@_#{name}_content|| '') + capture_block(&block)" end end end