追加到content_tag里的yield结果如何?

3
假设我有这个帮助程序在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>

但事实上,带有文本“this is the end”的跨度不会附加到产出物中。

如果我在助手中使用这行:

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

我会获取所有的内容,但是产生的结果会被包裹在另一个div中。

如何在yield后添加/追加内容,而不需要将yield包裹在不同的content_tag中?

1个回答

9
您可以使用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 %>

运行得很好!谢谢。yield到底有什么作用呢?我猜capture会把它变成字符串对吧? - Marcus Brunsten
1
yield在这个例子中与block.call相同,它执行给定的块,然后产生结果返回值。capture返回块内渲染的内容,以便您可以将其存储在变量中或对其进行操作。 - fivedigit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接