# Partial Hugo to generate a Table of Contents with \`\<details\>\` and \`\<summary\>\`

**URL:** <https://discourse.gohugo.io/t/partial-hugo-to-generate-a-table-of-contents-with-details-and-summary/51961>\
**Category:** tips & tricks\
**Tags:** toc\
**Created:** [October 15, 2024, 10:25am UTC](https://discourse.gohugo.io/t/partial-hugo-to-generate-a-table-of-contents-with-details-and-summary/51961 "2024-10-15T10:25:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lgrdev](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.gohugo.io/lgrdev/32/23090_2.png) [@lgrdev](https://discourse.gohugo.io/u/lgrdev)\
**Post date:** [October 15, 2024, 10:25am UTC](https://discourse.gohugo.io/t/partial-hugo-to-generate-a-table-of-contents-with-details-and-summary/51961/1 "2024-10-15T10:25:39Z")

</div>

Hello everyone,

I wanted to share a partial I created to dynamically generate a Table of Contents (ToC) in Hugo, using the HTML `<details>` and `<summary>` tags for an expandable/collapsible effect.

The code first checks if the `toc` variable is enabled in the page’s frontmatter. Then, it detects the `<h2>` tags within the content. If only one `<h2>` tag is found, it switches to using `<h3>` tags instead. Links are automatically generated for each heading based on the IDs found in the HTML.

Here’s the code for the partial `mytoc.html`:

```html
{{ if (eq $.Params.toc true)}}
<details class="notices tip">
  <summary class="label">Table of Contents</summary>
  <ul>
    {{ $headings := findRE "<h2.*?>(.|\n])+?</h2>" .Content }}
    {{ if (le (len $headings) 1) }}
      {{ $headings = findRE "<h3.*?>(.|\n])+?</h3>" .Content }}
    {{ end }}
    {{ range $headings }}
      {{ $id := findRE "id=\".*\"" . }}
      <li><a href="#{{ $id }}">{{ . | htmlUnescape | plainify }}</a></li>
    {{ end }}
  </ul>
</details>
{{ end }}

```

![Capture d’écran 2024-10-15 122431](https://canada1.discourse-cdn.com/flex036/uploads/gohugo/original/3X/f/f/ffa7508a7c2b4dc71c30b977f3d3ea31b558459a.png)

---

<div class="post-metadata">

**Author:** ![CyrusYip](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.gohugo.io/cyrusyip/32/20786_2.png) [@CyrusYip](https://discourse.gohugo.io/u/CyrusYip)\
**Post date:** [October 15, 2024, 4:08pm UTC](https://discourse.gohugo.io/t/partial-hugo-to-generate-a-table-of-contents-with-details-and-summary/51961/2 "2024-10-15T16:08:22Z")

</div>

You can use `.TableOfContents`.

> **[TableOfContents](https://gohugo.io/methods/page/tableofcontents/)**
>
> Returns a table of contents for the given page.
