Nesting content_tag in Rails 3

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

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.