Jekyll: Place the kramdown table of contents in an _include for hash navigation

1.7k Views Asked by At

I want to introduce hash links to the headings of a page into the menu of a web page. The web page is generated with Jekyll and it's default layout looks as follows:

<!DOCTYPE html>
<html>

  {% include head.html %}

  <body>

    {% include header.html %}

    <div id="BigFatContainer">
        {{ content }}
        {% include footer.html %}
    </div>
  </body>
</html>

It is in the header that the menu for navigating to the different pages is located. I've been able to add a table of contents to the {{ content }} with the help of the following Kramdown command:

* Point at which the TOC is attached
{:toc}

One could use some ugly JavaScript hack to move this table of contents from the {{ content }} and into header.html but that'd be a bad solution. It's not possible to place the {:toc} macro inside header.html since that's not parsed by Kramdown, and even if you make sure that it's parsed by Kramdown using for example this plugin it outputs the TOC of header.md instead of the TOC for the content.

3

There are 3 best solutions below

0
On BEST ANSWER

@miroslav-nedyalkov was on the right track here. Following his suggestion of looking at the Bootstrap documentation, I found that it uses a Ruby Gem - jekyll-toc that allows you to place a TOC anywhere in a layout file. You enable it in the front matter. I'm now successfully using:

<nav aria-label="Table of Contents">
    {{ content | toc_only }}
</nav>

<section itemprop="articleBody">
    {{ content }}
</section>
3
On

Why moving the toc block ?

This is correct to say that this toc is part of the page content. Semantically speaking.

You problem here is not at the document structure level but at the presentational one.

In this case the use of CSS is recommended to solve your problem.

2
On

I would suggest you to use the approach Bootstrap website (scroll down and observe the right navigation area) is using - make your TOC as part of the content area, but style it to be placed on the side like main navigation. The main reason I'm suggesting you this approach is that you may (and most probably will) have more than one page. In this case you will need to display different page navigation for every page and display some navigation between the pages.

For more information you may refer to this article - http://idratherbewriting.com/2015/01/20/implementing-scrollspy-with-jekyll-to-auto-build-a-table-of-contents/