The capture method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
Examples
The capture method can be used in ERb templates…
<% @greeting = capture do %> Welcome to my shiny new web page! The date and time is <%= Time.now %> <% end %>
…and Builder (RXML) templates.
@timestamp = capture do "The current timestamp is #{Time.now}." end
You can then use that variable anywhere else. For example:
<html> <head><title><%= @greeting %></title></head> <body> <b><%= @greeting %></b> </body></html>
Source Code
# File action_view/helpers/capture_helper.rb, line 33 def capture(*args, &block) # execute the block begin buffer = eval(ActionView::Base.erb_variable, block.binding) rescue buffer = nil end if buffer.nil? capture_block(*args, &block).to_s else capture_erb_with_buffer(buffer, *args, &block).to_s end end
<code/>and<pre/>for code samples.