ruby-on-rails - 如何使用 block 创建助手?

标签 ruby-on-rails ruby helper

我想做一个像下面这样的助手。

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

最佳答案

你应该使用 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。 如果您需要捕获然后重用内容,请使用捕获。如果您的 block 没有明确使用 <%=,那么您必须调用 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 %>

关于ruby-on-rails - 如何使用 block 创建助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1047861/

相关文章:

java - return 语句之前的局部变量,这有关系吗?

ruby-on-rails - Rails服务对象和错误

ruby-on-rails - 每次部署后回形针文件都会被删除

javascript - Rails js.erb 追加 block link_to

ruby - 为 Sinatra 生成 JSON

java - Scala:如果字符串为空,是否有帮助程序获取 Option[String]?

ruby-on-rails - 使用关系数据库

ruby - cert.pem 的 RVM 证书目录

ruby - 获取 Facebook 好友的位置非常耗时

PHP:关闭 SoapClient 连接是否更好?