Search code examples
ruby-on-rails

Helper method renders no list items


In Rails 7, why the following helper doesn't render the list items?

def list(options)
  tag.ul(class: "a") do
    options.each do |option|
      tag.li(class: "b") do
        tag.span(option, class: "c")
      end
    end
  end
end

I call <%= list(["X", "Y", "Z"]) %> and what is rendered is simply <ul class="a"></ul>.

What am I missing here?


Solution

  • Normally, with erb you'd write this:

    <%= tag.ul(class: "a") do %>
      <% ["X", "Y", "Z"].each do |option| %>
        <%= tag.li(class: "b") do %>         # <%= %> is the same as `concat`
          <%= tag.span(option, class: "c") %>
        <% end %>
      <% end %>
    <% end %>
    

    Using concat:

    def list(options)
      tag.ul(class: "a") do
        options.each do |option|
          concat(
            tag.li(class: "b") do
              # concat could be omitted here for a single tag
              concat tag.span(option, class: "c")
            end
          )
        end
      end
    end
    

    Using safe_join:

    def list(options)
      tag.ul(class: "a") do
        safe_join(
          options.map do |option|
            tag.li(class: "b") do
              tag.span(option, class: "c")
            end
          end
        )
      end
    end