Nesting content_tag in Rails 3

Gabe Berke-Williams

Nesting content_tag in Rails 3 is counter-intuitive. This looks like it will work:

content_tag(:ul) do
  collection.map do |item|
    content_tag(:li, item.title)
  end
end

But it doesn’t. You get an empty list:

<ul>
</ul>

What’s the deal? To fix it, use the concat method:

content_tag(:ul) do
  collection.map do |item|
    concat(content_tag(:li, item.title))
  end
end

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.