There are many examples on the web on how to generate multi-level menus with handlebars. The problem is that they are often based on the following data structure :
var headings = [
{ id: "foo1", tag: "h1", text: "foo1 text", items: [
{ id: "foo11", tag: "h2", text: "foo11 text" },
{ id: "foo12", tag: "h2", text: "foo12 text" }
]},
{ id: "foo2", tag: "h1", text: "foo2 text" },
{ id: "foo3", tag: "h1", text: "foo3 text" }
];
As you can see, submenus are embedded in their parent menu.
metalsmith-headings generates a flat data structure :
var headings = [
{ id: "foo1", tag: "h1", text: "foo1 text" },
{ id: "foo11", tag: "h2", text: "foo11 text" },
{ id: "foo12", tag: "h2", text: "foo12 text" },
{ id: "foo2", tag: "h1", text: "foo2 text" },
{ id: "foo3", tag: "h1", text: "foo3 text" }
];
It is then harder to generate a correct menu with handlebars.
I'd like to get something like this in html :
<!-- toc -->
<div class="col-md-3">
<div class="sidebar hidden-print affix-top toc" role="complementary">
<ul class="nav sidenav">
<li ><a href="#foo1">foo1 text</a>
<ul class="nav">
<li class=""><a href="#foo11">foo11 text</a></li>
<li class=""><a href="#foo12">foo12 text</a></li>
</ul>
</li>
<li><a href="#foo2">foo2 text</a></li>
<li><a href="#foo3">foo3 text</a></li>
</ul>
</div>
</div>
As you can see, sublist ul
is embedded in its parent li
.
I manage to start something that works a little bit. But there is large flaws to improve. I'm not an expert in js, nor in handlebars. You can see a working test the following JSFiddle example.
Mains flaws are :
- I'm not sure the generated html would be correct in any cases
- html is generated by helper whereas it should be generated by the template
Feel free to share your thinking, to improve my solution, and to discuss about the data structure that metalsmith-headers should generate.