Add Page.FirstSection
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Mon, 23 Jul 2018 18:19:32 +0000 (20:19 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Mon, 23 Jul 2018 18:20:19 +0000 (20:20 +0200)
It was added and then removed by accident some time ago. Let us add it again, as it is useful.

hugolib/site_sections.go
hugolib/site_sections_test.go

index b87388c59ebade21a7ec77e099e00d368676a8b6..2a92a342438fd2b2a48226815e69d44df0c46ddf 100644 (file)
@@ -58,6 +58,29 @@ func (p *Page) CurrentSection() *Page {
        return v.parent
 }
 
+// FirstSection returns the section on level 1 below home, e.g. "/docs".
+// For the home page, this will return itself.
+func (p *Page) FirstSection() *Page {
+       v := p
+       if v.origOnCopy != nil {
+               v = v.origOnCopy
+       }
+
+       if v.parent == nil || v.parent.IsHome() {
+               return v
+       }
+
+       parent := v.parent
+       for {
+               current := parent
+               parent = parent.parent
+               if parent == nil || parent.IsHome() {
+                       return current
+               }
+       }
+
+}
+
 // InSection returns whether the given page is in the current section.
 // Note that this will always return false for pages that are
 // not either regular, home or section pages.
index 603f2898cad40f95629f36de724a0ed9e2709ee1..bfec623e52fd73c62f65eb37d9334c00d3f282ec 100644 (file)
@@ -176,6 +176,7 @@ PAG|{{ .Title }}|{{ $sect.InSection . }}
                        active, err := home.InSection(home)
                        assert.NoError(err)
                        assert.True(active)
+                       assert.Equal(p, p.FirstSection())
                }},
                {"l1", func(p *Page) {
                        assert.Equal("L1s", p.title)
@@ -249,6 +250,7 @@ PAG|{{ .Title }}|{{ $sect.InSection . }}
                        isAncestor, err = p.IsAncestor(l1)
                        assert.NoError(err)
                        assert.False(isAncestor)
+                       assert.Equal(l1, p.FirstSection())
 
                }},
                {"perm a,link", func(p *Page) {