Reputation: 1370
I'm trying to plan out the design of a page using Bootstrap 4 in Ruby on Rails for a sidebar submenu that will need to expand/collapse, have some bullet points, and contain a counter.
So ultimately it needs to look like:
Alpha 4000
* Major One 2000
Minor One 500
Minor Two 1500
* Major Two 1000
Right now I'm thinking of it in terms of HTML/CSS in terms of an unordered list like:
<ul>
<li><a href="menu1" data-toggle="collapse">Major One</a></li>
<ul class="collapse" id="menu1">
<li>Minor One</li>
<li>Minor Two</li>
</ul>
</li>
<li>Major Two</li>
</ul>
I realized that I need to put in some form of counter in the unordered list and possibly split the columns on the ul li tags that I realized...there HAS to be a Ruby way of handling this. Is there a cleaner, Ruby way, of creating an unordered list that has two columns with collapse and a count?
Upvotes: 0
Views: 103
Reputation: 102026
Start by setting up a basic data structure:
@things = [
{
label: "Alpha",
counter: 4000,
children: [
{
label: "Major One",
count: 2000,
children: [
{ label: "Minor One", count: 500 },
{ label: "Minor two", count: 1500 }
]
},
{
label: "Major One",
count: 1500
}
]
}
]
Then use a partial to recursively create lists of lists:
# layouts/application.html.erb
<ul>
<%= render partial: 'menu_item', collection: @things, as: :item, locals: { level: 1 } %>
<ul>
# app/views/things/_menu_item.html.erb
<li class="<%= "level-#{level} n-#{item_counter}" %>">
<a href="#"><%= item[:label] %></a>
<% if item[:children] %>
<ul class="collapse">
<%= render partial: 'menu_item',
collection: item[:children],
as: :item,
locals: { level: level + 1 }
%>
</ul>
<% end %>
</li>
class: "level-#{level} n-#{item_counter}"
is just an example of how you can keep track of what level you are at and the index.
The output is:
<ul>
<li class="level-1 n-0">
<a href="#">Alpha</a>
<ul>
<li class="level-2 n-0">
<a href="#">Major One</a>
<ul>
<li class="level-3 n-0">
<a href="#">Minor One</a>
</li>
<li class="level-3 n-1">
<a href="#">Minor two</a>
</li>
</ul>
</li>
<li class="level-2 n-1">
<a href="#">Major One</a>
</li>
</ul>
</li>
<ul>
You can of course add more keys to the hash structure to provide href´s, wrapper classes and link classes etc.
Upvotes: 1