How to set `TableOfContents` markup configurations for a single post?

TableOfContents allows setting endLevel site-wide. How can I change the endLevel only for a particular post? I tried adding the following to the front matter but it doesn’t seem to do anything:

markup:
  tableOfContents:
    endLevel: 2
    ordered: false
    startLevel: 2

This seems to also have been asked a few years ago with no answer: TableOfContents: Custom markup params for individual page? - #6 by exprez135

Use .Page.Fragments.ToHTML instead.

Use .Page.Param to check for custom params in front matter, falling back to custom params in your site configuration, falling back to default values as shown in the partial below.

layouts/partials/toc.html
{{ if .Params.toc }}
  {{ $startLevel := or (.Param "toc.startLevel") 2 }}
  {{ $endLevel := or (.Param "toc.endLevel") 3 }}
  {{ $ordered := or (.Param "toc.ordered") false }}
  {{ .Fragments.ToHTML $startLevel $endLevel $ordered }}
{{ end }}

The above requires v0.139.4 or later. See Issue #13107.

layouts/_default/single.html
{{ define "main" }}
  <h1>{{ .Title }}</h1>
  {{ partial "toc.html" . }}
  {{ .Content }}
{{ end }}

hugo.toml
[params.toc]
startLevel = 2
endLevel = 3
ordered = false

To enable the TOC on the page:

+++
title = 'Post 1'
date = 2024-12-03T22:03:26-08:00
toc = true
+++

To enable the TOC on the page and set or override the toc parameters.

+++
title = 'Post 1'
date = 2024-12-03T22:03:26-08:00
[params.toc]
startLevel = 3
endLevel = 5
ordered = true
+++

In front matter you can set or override zero or more of the toc parameters. You don’t have to specify all of them. For example:

+++
title = 'Post 1'
date = 2024-12-03T22:03:26-08:00
[params.toc]
endLevel = 4
+++
2 Likes

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