diff --git a/modules/markup/html.go b/modules/markup/html.go
index 1c2ae6918d..c2339838e5 100644
--- a/modules/markup/html.go
+++ b/modules/markup/html.go
@@ -254,26 +254,35 @@ func RenderTocHeadingItems(ctx *RenderContext, nodeDetailsAttrs map[string]strin
currentLevel := baseLevel
indent := []byte{' ', ' '}
_, _ = htmlutil.HTMLPrint(out, "
\n")
- for _, header := range ctx.TocHeadingItems {
+ for i, header := range ctx.TocHeadingItems {
+ // Go deeper: open nested elements (wrapped in - for valid HTML)
for currentLevel < header.HeadingLevel {
_, _ = out.Write(indent)
- _, _ = htmlutil.HTMLPrint(out, "
\n")
+ _, _ = htmlutil.HTMLPrint(out, "\n")
indent = append(indent, ' ', ' ')
currentLevel++
}
+ // Go shallower: close nested
elements
for currentLevel > header.HeadingLevel {
indent = indent[:len(indent)-2]
_, _ = out.Write(indent)
- _, _ = htmlutil.HTMLPrint(out, "
\n")
+ _, _ = htmlutil.HTMLPrint(out, "
\n")
currentLevel--
}
_, _ = out.Write(indent)
- _, _ = htmlutil.HTMLPrintf(out, "- %s
\n", header.AnchorID, header.InnerText)
+ _, _ = htmlutil.HTMLPrintf(out, "- %s", header.AnchorID, header.InnerText)
+ // Check if next item is at a deeper level - if so, don't close the
- yet
+ nextIsDeeper := i+1 < len(ctx.TocHeadingItems) && ctx.TocHeadingItems[i+1].HeadingLevel > header.HeadingLevel
+ if !nextIsDeeper {
+ _, _ = htmlutil.HTMLPrint(out, "
")
+ }
+ _, _ = htmlutil.HTMLPrint(out, "\n")
}
+ // Close any remaining nested levels
for currentLevel > baseLevel {
indent = indent[:len(indent)-2]
_, _ = out.Write(indent)
- _, _ = htmlutil.HTMLPrint(out, "
\n")
+ _, _ = htmlutil.HTMLPrint(out, "\n")
currentLevel--
}
_, _ = htmlutil.HTMLPrint(out, "\n\n")
diff --git a/modules/markup/html_toc_test.go b/modules/markup/html_toc_test.go
index e93cfc9346..ab363878a4 100644
--- a/modules/markup/html_toc_test.go
+++ b/modules/markup/html_toc_test.go
@@ -38,16 +38,16 @@ include_toc: true
result = re.ReplaceAllString(result, "\n")
expected := `toc