Table Of Content HTML partial

Is it possible to customize the HTML markup of how the TOC renders? Currently, it only renders the anchor without the page’s permalink rendering this feature unusable.

I’ve tried making a render-link and a toc partial but that does not seem to produce what I want.

It would be great if we could range {{.TableOfContents}} and render it however we choose instead of hugo deciding how to render it.

I’m going to make this a feature request in the meantime if anyone knows how to accomplish this I would greatly appreciate any insight.

Thanks.

Just leaving this here in case anyone else is looking to solve this issue, here is how I fixed it using javascript.

// get all page headers

var headings = document.querySelectorAll("h1, h2, h3, h4, h5, h6");

// table of contents container typically a: <ul id=""toc"></ul>

var tableOfContents = document.querySelector("#toc");

// function to render TOC

function renderTOC () {
  var toc = [...headings].map(link => `<li>${link.innerHTML}</li>`).join('');
  return tableOfContents.innerHTML = toc;
}

renderTOC();

And this is what my render-heading.html template looks like in order to fix proper anchor links:

<h{{ .Level }} id="{{ .Anchor | safeURL }}"><a href="{{.Page.URL}}#{{ .Anchor | safeURL }}" class="has-text-black">{{ .Text | safeHTML }}</a></h{{ .Level }}>

Hopefully, this will help others.

bumping this. i really love the _markup/render-codeblock.html functionality that we have for headers, images, etc… could we get one for _markup/render-toc.html?

I’m not convinced there would be much value to a render hook for the Table of Contents (TOC), primarily due to the limitations of the existing .TableOfContents method.

The right way to generated a TOC is after the HTML has been written to the public directory.

  1. Generate the TOC with JavaScript (tocbot.js, etc.)
  2. Generate the TOC with a partial as suggested here
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.