Rails content_tag for <ul> element

8.9k Views Asked by At

How would I get the following html output with the content_tag helper?

  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>

This is what I have currently

  content_tag(:ul) do
    a=*(1..5)
    a.each do |step_number|
      content_tag(:li, class: "step") do
        puts step_number
      end
    end
  end

Update - Answer

Thanks to Peter's Loop & output content_tags within content_tag in helper link below, I was missing concat on the li items

  content_tag :ul do
    items.collect do |step_number|
      concat(content_tag(:li, step_number, class: "step"))
    end
  end
2

There are 2 best solutions below

3
On

I guess all you have to fix is

content_tag(:ul) do
  (1..5).to_a.map do
    content_tag(:li, step_number, class: "step)
  end.reduce(&:+)
end

That should do the job!

0
On

it works for me.

content_tag(:ul, :class => 'a class') do
  (1..5).each do |item|
    concat content_tag(:li, item)
  end
end

<ul class="a class">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>