All pages by section (including page bundles)

Figured I would drop this snippet in, having spent the time to develop it.

I needed a template showing FOR A GIVEN PAGE BUNDLE all pages by section, including both leaf bundles and page bundles. There are a number of posts that approach this via .Site.Pages, filtering by section, omitting page-bundles, etc. But they all work off the top-level section instead of subsections.

Caveat: This is not recursive, so it will omit sub-sub-sub-sections (page bundles in page bundles).

            {{ $sectionIndex := -1 }}

            {{ range .Sections }}
                {{ $sectionIndex = add $sectionIndex 1 }}
                {{ $curSection := . }}

                {{ $allPgs := append $curSection.Sections $curSection.Pages }}

                {{/* now get pgs of sections */}}
                {{ range $curSection.Sections}}
                    {{ $allPgs = append $allPgs .Pages }}
                {{ end }}
                <h2>{{ $curSection }} <span class="small text-white">({{ len $allPgs }} pgs)</span></h2>

               <ul class="list-unstyled">
                                {{ range sort $allPgs "File.Path"}}
                                <li>
                                    <a href="{{ .Permalink }}" target="coursePage"
                                       data-toggle="tooltip" data-placement="bottom" title="{{ .LinkTitle }}">{{.File.Path}}</a>
                                </li>
                                {{ end }}
                            </ul>
            {{ end }}

From a recent version we changed it so $curSection.Pages also includes section, which should make your code a little simpler. $curSection.RegularPages returns only the leaf pages.