诗歌rails之 concat , capture

The preferred method of outputting text in your views is to use the <%= "text" %> eRuby syntax. The regular puts and print methods do not operate as expected in an eRuby code block. If you absolutely must output text within a non-output code block (i.e., <% %>), you can use the concat method.

Examples

  <%
      concat "hello"
      # is the equivalent of <%= "hello" %>
      if (logged_in == true):
        concat "Logged in!"
      else
        concat link_to('login', :action => login)
      end
      # will either display "Logged in!" or a login link
  %>
    # File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 27
27:       def concat(string, unused_binding = nil)
28:         if unused_binding
29:           ActiveSupport::Deprecation.warn("The binding argument of #concat is no longer needed.  Please remove it from your views and helpers.", caller)
30:         end
31: 
32:         output_buffer << string
33:       end

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:
<%= @greeting %>

    # File vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb, line 33
33:       def capture(*args, &block)
34:         # Return captured buffer in erb.
35:         if block_called_from_erb?(block)
36:           with_output_buffer { block.call(*args) }
37:         else
38:           # Return block result otherwise, but protect buffer also.
39:           with_output_buffer { return block.call(*args) }
40:         end
41:       end
posted @ 2009-07-08 15:22  麦飞  阅读(323)  评论(0编辑  收藏  举报