-
-
Notifications
You must be signed in to change notification settings - Fork 201
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Combine headers of all pages before generating TOC
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
Showing
1 changed file
with
27 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }} |