在content_tag中追加到yield

时间:2015-10-07 06:42:25

标签: ruby-on-rails ruby

假设我在application_helper.rb

中有这个助手
def my_helper(content = nil, *args, &block)
   content_tag(:div, class: :my_wrapper) do
      (block_given? ? yield : content) + content_tag(:span, "this is the end", *args)
   end
end

我从

的视图中调用它
my_helper do 
  content_tag(:div, "this is the beginning")
end

我希望结果类似于

<div class="my_wrapper">
    <div>
       this it the beginning
    </div>
    <span>
       this is the end
    </span>
</div>

但实际上,带有“这就是结束”字样的跨度不会附加到收益率上。

如果我在帮助器中使用此行:

(block_given? ? content_tag(:div, &block) : content) + content_tag(:span, "this is the end", *args)

我会得到两个内容,但收益率将包含在另一个div中。

如何在收益后添加/追加内容,而不将收益率包含在不同的content_tag中?

1 个答案:

答案 0 :(得分:6)

您可以使用capture来实现此目标:

def my_helper(content = nil, *args, &block)
  content_tag(:div, class: :my_wrapper) do
    (block_given? ? capture(&block) : content) + content_tag(:span, "this is the end", *args)
  end
end

请务必在您的观点中执行此操作:

<%= my_helper do %>
  <%= content_tag(:div, "this is the beginning") %>
<%- end %>