When generating the TableOfContent for a different page than the current one, the href links do not respect the link to the actual href to the page. Instead a anchor on the current site is used (which obviously cannot be found).
For example here I generate the TableOfContent for the current page and then the TableOfContent for other related pages. But the hrefs to these pages do not work:
The TableOfContents method creates a nested list of links that are relative to the current page. When you’re ranging through a collection of regular pages on a list page, the “current page” is not the list page.
You need to walk the page’s Fragments.Headings to build your own table of contents. I’ve written about this before:
git clone --single-branch -b hugo-github-issue-13482 https://github.com/jmooring/hugo-testing hugo-github-issue-13482
cd hugo-github-issue-13482
hugo server
Files of interest:
layouts/partials/toc-walk-headings.html (copied from the article above)
layouts/_default/home.html (line 14)
hugo.toml (lines 5-13, see below)
[params.toc]
startLevel = 2 # default is 2
endLevel = 3 # default is 3
minNumHeadings = 2 # default is 2
[cascade]
toc = true # enable toc for all pages
[cascade.target]
kind = 'page'
In the above, the first block configures TOC behavior.
The second block enables the TOC for all pages. Without the second block, you would need to opt-in to TOC creation on a page-by-page basis by setting toc = true in front matter. Read the comments at the top of the toc-walk-headings.html partial for more details.
Edit: I changed the topic title from “TableOfContent does not respect the current context” to “Ranging over tables of content on a list page” because the TableOfContentsdoes respect the current context. This topic is about creating a table of contents with site-relative links (path + fragment) instead of page-relative links (fragment only).
Hi Joe,
thanks for your reply and sorry for mixing up the site and page context. However I still think it could be a good feature, if the toc creation would create proper links if it generates the toc for a different page. As the headings are created correctly but not the links.
Anyway much thanks for your article and example. It’s a great possibility to change formatting, style and content of the toc. This is a good starting position for more customized tocs in our project