Collapsible directory

I’m trying to create a directory structure where the third level is collapsed unless the parent or any of its children are the active page. I can get it to work locally using a few different methods, however in the deploy preview the “closed folders” are always open regardless of what I do.

(also, if there’s a way to do this kind of nesting without repeating myself for every level, please let me know haha)

{{ if .IsHome}}
{{else}}

    {{$index := .Section}}
    {{$currentPage := . }}
    {{$currentSection := .CurrentSection.Title}}

<nav class="is-one-fifth is-hidden-mobile  xs">
    {{ with .Site.GetPage "section" $index }}
        <div class="sticky pt-5 h-scroll noscrollbar">
            {{ range .Pages }}
            <div class="border-image-l-2 listless pl-6 mb-4">
                <div class="mb-1 m bold"><a href="{{.RelPermalink}}">{{ if eq $currentPage.RelPermalink .RelPermalink}} > {{end}}{{ .Title }}</a>
                
                    {{ if (eq .Params.layout "glossary") }}
                    {{/*  Does not display children if parent has layout:glossary  */}}
                    {{else if .Pages }}
                        {{ range .Pages }}
                        <div class="ml-2 mb-2 my-2 s semi-bold  "><a href="{{.RelPermalink}}">{{ if eq $currentPage.RelPermalink .RelPermalink}} > {{end}}{{ .Title }}</a>
                        
                            {{ if (eq .Params.layout "glossary") }}
                            {{/*  Does not display children if parent has layout:glossary  */}}
                            {{else if .Pages }}
        
                                {{ range .Pages }}
                                <div class="ml-4 mb-2 my-2 xs normal {{if eq $currentSection .Parent.Title}} {{else}} closed-folder{{end}}"><a href="{{.RelPermalink}}">{{ if eq $currentPage.RelPermalink .RelPermalink}} > {{end}} {{ .Title }}</a></div>
                                {{end}}
                            {{ end }}
                        
                        </div>
                        {{end}}
                    {{ end }}
                </div>
            </div>
        
            {{ end }}

        </div>
    {{end}}
</nav>

{{end}}