Construct an unordered list with content_tag

Asked

Viewed 199 times

1

How to build a list containing sublists using the content_tag rails?

Using the method in the Helper does not work.

<ul class="menu">
 <li>Item1
  <ul>
   <li><a href="#>Link1</a></li>
   <li><a href="#>Link2</a></li>
   <li><a href="#>Link3</a></li>
  </ul>
 </li>
</ul>

2 answers

2

With this code you can create the list:

def li_with_link(link_text, link_url)
  content_tag :li, link_to(link_text, link_url)
end

def ul_with_lis
  content_tag :ul, class: 'menu' do
    content_tag :li do
      "Item1" + li_with_link("link1", '#') + li_with_link("link2", '#')
    end
  end
end

Note: If your idea is to simplify, use ERB even better!

Take a look at the method documentation as well: http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag

  • I believe the editing of my answer is incorrect. How we concatenate String with ActiveSupport::SafeBuffer, the result will be a String

1

Rodrigo’s tip has a problem: each link will have a UL + LI, but I agree with him that using ERB (or HAML, or SLIM) is better. If for some reason you need to do this with ruby, maybe this will help:

def menu(links = [])
  content_tag :ul do
    links.map do |link|
      content_tag :li do
        link_to link[:label], link[:href]
      end
    end
  end
end

calling for:

<% links = [] %>
<% links << { label: 'google', href: 'https://google.com' } %>
<% links << { label: 'facebook', href: 'https://facebook.com' } %>
<% links << { label: 'twitter', href: 'https://twitter.com' } %>
<% links << { label: 'logout', href: logout_path %>
<%= menu(links) %>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.