Skip to content

Commit

Permalink
Combine headers of all pages before generating TOC
Browse files Browse the repository at this point in the history
By combining all the headers scattered around all the different
pages, before looping over them to generate the ToC, we can now
safely distribute the contents on multiple smaller files. e.g:

```
10-main.md (define h1)
11-sub1.md (define h2 and multiple h3)
12-sub2.md (define h2)
20-second.md (define h1 and multiple h2 and h3)
21-sub1.md (define h2)
```
  • Loading branch information
khos2ow authored and bep committed Nov 7, 2019
1 parent ff1c02c commit 2c5e656
Showing 1 changed file with 27 additions and 24 deletions.
51 changes: 27 additions & 24 deletions layouts/partials/funcs/toc_from_pages.html
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
{{ $toc := slice }}
{{ $combined := slice }}
{{ range . }}
{{ $previousH1 := dict}}
{{ $previousLevel := 0 }}
{{ $h2s := slice }}

{{ $headers := findRE "<h\\d.*?>(.|\n)*?</h\\d>" .Content }}
{{ range $headers }}
{{ $level := int (substr . 2 1) }}
{{ if le $level 2 }}
{{ $title := . | replaceRE "</?h\\d.*?>" "" | htmlUnescape | safeHTML }}
{{ $item := dict "level" $level "title" $title }}
{{ $combined = $combined | append $headers }}
{{ end }}

{{if eq $level 1 }}
{{if ne $previousLevel 0 }}
{{ $tocItem := merge $previousH1 (dict "sub" $h2s)}}
{{ $toc = $toc | append $tocItem }}
{{ $h2s = slice }}
{{end}}
{{ $previousH1 = $item }}
{{else}}
{{ $h2s = $h2s | append $item}}
{{ $toc := slice }}
{{ $previousH1 := dict }}
{{ $previousLevel := 0 }}
{{ $h2s := slice }}

{{ range $combined }}
{{ $level := int (substr . 2 1) }}
{{ if le $level 2 }}
{{ $title := . | replaceRE "</?h\\d.*?>" "" | htmlUnescape | safeHTML }}
{{ $item := dict "level" $level "title" $title }}

{{ if eq $level 1 }}
{{ if ne $previousLevel 0 }}
{{ $tocItem := merge $previousH1 (dict "sub" $h2s) }}
{{ $toc = $toc | append $tocItem }}
{{ $h2s = slice }}
{{end}}
{{ $previousLevel = $level }}
{{ $previousH1 = $item }}
{{ else }}
{{ $h2s = $h2s | append $item }}
{{ end }}
{{ $previousLevel = $level }}
{{ end }}
{{if ne $previousLevel 0}}
{{ $item := merge $previousH1 (dict "sub" $h2s)}}
{{ $toc = $toc | append $item }}
{{end}}
{{ end }}
{{ if ne $previousLevel 0 }}
{{ $item := merge $previousH1 (dict "sub" $h2s) }}
{{ $toc = $toc | append $item }}
{{ end }}
{{ return $toc }}

0 comments on commit 2c5e656

Please sign in to comment.