How to know the section depth

I am doing a TOC for my content folder. Where I have different view for every level/depth of sections.
My question is how can I know the depth of a particular section/folder.

For example

content
└── docs   ////// level1
    ├── doc1-folder  
          └── d1_a.md      //// level 2
          
 
    └── doc2-folder    /// level 2
          └── d2_a.md      /// 
          └── doc3-folder
                   └── d3_a.md   ///  level 3

How can I know these levels ? I am looping the section using range , Do we have any parameter using which I can know the level/ depth of the section and perform action accordingly.

It’s not a complete answer, but would .File.Path used with split and len help?

Good thinking, but that will fail with leaf bundles. So then you look at .RelPermalink instead, but that’s subject to user modification through front matter (url) and site configuration (permalinks).

To render the section depth as follows:

content/
├── s1/
│   ├── s1-1/
│   │   ├── s1-1-1/
│   │   │   ├── foo.md    --> section depth = 3
│   │   │   └── _index.md --> section depth = 3
│   │   ├── foo.md        --> section depth = 2
│   │   └── _index.md     --> section depth = 2
│   ├── foo.md            --> section depth = 1
│   └── _index.md         --> section depth = 1
├── foo.md                --> section depth = 0
└── _index.md             --> section depth = 0

Use this partial:

layouts/partials/render-section-depth.html
{{ $page := . }}
{{ $depth := 0 }}

{{ if reflect.IsMap . }}
 {{ $page = .page }}
 {{ $depth = .depth }}
{{ end }}

{{ with $page.Parent }}
  {{ if $page.IsSection }}
    {{ $depth = add $depth 1 }}
  {{ end }}
  {{ partial "render-section-depth" (dict "page" . "depth" $depth) }}
{{- else }}
  {{ $depth }}
{{- end }}
{{- /**/ -}}
2 Likes

@jmooring Seems to be promising, but for some reason it is counting for every section as previous count +1

Try this and see if it behaves as you expect.

git clone --single-branch -b hugo-forum-topic-37302 https://github.com/jmooring/hugo-testing hugo-forum-topic-37302
cd hugo-forum-topic-37302
hugo server

Also, are you passing the page context to the partial? Example:

{{ partial "render-section-depth.html" . }}

@jmooring Its working. Thanks!! Sorry, there was some mistake with my {{ template }}

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