在content_tag中追加到yield

Mar*_*ten 2 ruby ruby-on-rails

可以说我有这个帮手 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
Run Code Online (Sandbox Code Playgroud)

我从一个视角来称呼它

my_helper do 
  content_tag(:div, "this is the beginning")
end
Run Code Online (Sandbox Code Playgroud)

我希望结果是这样的

<div class="my_wrapper">
    <div>
       this it the beginning
    </div>
    <span>
       this is the end
    </span>
</div>
Run Code Online (Sandbox Code Playgroud)

但实际上,带有"这就是结束"的文本的范围不会附加到收益率上.

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

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

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

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

fiv*_*git 8

你可以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
Run Code Online (Sandbox Code Playgroud)

并确保在您的视图中执行此操作:

<%= my_helper do %>
  <%= content_tag(:div, "this is the beginning") %>
<%- end %>
Run Code Online (Sandbox Code Playgroud)