Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to yield in content_tag

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?

like image 250
Marcus Brunsten Avatar asked Sep 02 '25 05:09

Marcus Brunsten


1 Answers

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 %>
like image 186
fivedigit Avatar answered Sep 04 '25 23:09

fivedigit