Back

Nesting the rails content_tag helper

I was working on a rails application that needed to present some data as an HTML list with multiple levels. Something like:

<ul>
  <li>first-item</li>
  <li>second-item</li>
</ul>

I was aware of the content_tag helper which can be used like so:

content_tag :li do
  "an item"
end

to produce:

<li>
  an item
</li>

Based on that pattern, I naively assumed that I could do something like this:

content_tag :ul do
  %w[first-item second-item].each do |item| 
    content_tag :li, item
  end
end

Which to my surprise produced only:

<ul></ul>

After a little research and trial/error, I realized that the content_tag helper operates on the return value of the block, which is an array in this case and content_tag apparently doesn’t do anything useful with arrays. The solution was to concat the output manually, like so:

content_tag :ul do
  %w[first-item second-item].each do |item| 
    concat content_tag :li, item
  end
end

And now the output is as expected:

<ul>
  <li>first-itm</li>
  <li>second-item</li>
</ul>

2 responses to “Nesting the rails content_tag helper”

  1. […] enough, things did not go quite as simply as I expected which gave me material for two blog posts: Nesting the rails content_tag helper and Nesting the content_tag helper more […]

  2. […] ← Nesting the rails content_tag helper Announcing the Listify Gem → […]

Leave a Reply

Your email address will not be published. Required fields are marked *