如何使用块创建帮助程序?

时间:2009-06-26 07:49:40

标签: ruby-on-rails ruby helper

我想做一个像以下一样的帮手。

def my_div some_options, &block
  # How do I print the result of the block?
end

3 个答案:

答案 0 :(得分:15)

您应该使用CaptureHelper

def my_div(some_options, &block)
  # capture the value of the block a string
  content = capture(&block)
  # concat the value to the output
  concat(content)
end

<% my_div([]) do %>
  <p>The content</p>
<% end %>


def my_div(some_options, &block)
  # capture the value of the block a string
  # and returns it. You MUST use <%= in your view.
  capture(&block)
end

<%= my_div([]) do %>
  <p>The content</p>
<% end %>

如果需要连接输出,请使用capture + concat。 如果需要捕获然后重用内容,请使用捕获。如果您的块没有明确地使用&lt;%=,那么您必须调用concat(首选方式)。

这是一个隐藏内容的方法示例,如果用户不是管理员。

def if_admin(options = {}, &block)
  if admin?
    concat content_tag(:div, capture(&block), options)
  end
end

<% if_admin(:style => "admin") do %>
<p>Super secret content.</p>
<% end %>

答案 1 :(得分:1)

http://www.rubycentral.com/book/tut_containers.html

yield语句将返回传递的块的结果。所以,如果你想打印(控制台?)

def my_div &block
  yield
end

my_div { puts "Something" } 

输出“Something”

但: 你的方法有什么想法?输出DIV?

答案 2 :(得分:0)

有两点很重要:

  • rails会忽略content_tag(和content_for)中不是字符串的任何内容
  • 您不能使用Array#join等,因为它会产生不安全的字符串,您需要使用safe_joincontent_tag来获得安全的字符串
  • 我不需要captureconcat
  def map_join(objects, &block)
    safe_join(objects.map(&block))
  end

  def list(objects, &block)
    if objects.none?
      content_tag(:p, "none")
    else
      content_tag(:ul, class: "disc") do
        map_join(objects) do |object|
          content_tag(:li) do
            block.call(object)
          end
        end
      end
    end
  end

可以这样使用:

= list(@users) do |user|
  => render user
  = link_to "show", user 

(这很苗条,但也可以和erb一起使用)

相关问题