Lets say I have this helper in 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
And i call it from a view with
my_helper do
content_tag(:div, "this is the beginning")
end
I would expect the result to be something like
<div class="my_wrapper">
<div>
this it the beginning
</div>
<span>
this is the end
</span>
</div>
But in fact, the span with the text "this is the end" will not be appended to the yield.
If i were to use this line in the helper instead:
(block_given? ? content_tag(:div, &block) : content) + content_tag(:span, "this is the end", *args)
I would get both content, but the yield would be wrapped inside another div.
How could I add / append content after a yield, without wrapping the yield in a different content_tag?
You can use capture
to achieve this:
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
And be sure to do this in your view:
<%= my_helper do %>
<%= content_tag(:div, "this is the beginning") %>
<%- end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With