page: Add GetPage function

This commit is contained in:
Adnan Maolood 2022-06-27 14:15:10 -04:00
parent 34935f7de8
commit 36bf485c1d
3 changed files with 32 additions and 22 deletions

View file

@ -13,7 +13,6 @@ import (
func (s *Site) funcs() map[string]interface{} {
return map[string]interface{}{
"exec": executeString,
"page": s.page,
"path": func() _path { return _path{} },
"partial": s.templates.ExecutePartial,
"reverse": reverse,

51
page.go
View file

@ -31,6 +31,7 @@ type Page struct {
Next *Page `yaml:"-"`
Pages []*Page `yaml:"-"`
Dirs []*Page `yaml:"-"`
pages map[string]*Page
feeds map[string][]byte
index bool
}
@ -64,6 +65,7 @@ func (p *Page) _read(fsys fs.FS, path string, task *Task, cfg *Site) error {
return err
}
p.Dirs = append(p.Dirs, dir)
p.addPage(name, dir)
} else if ext := pathpkg.Ext(name); task.Match(ext) {
// Ignore pages beginning with "_" with the exception of _index pages
namePrefix := strings.TrimSuffix(name, ext)
@ -163,12 +165,20 @@ func (p *Page) _read(fsys fs.FS, path string, task *Task, cfg *Site) error {
}
page.URL = task.URL + page.Path
p.Pages = append(p.Pages, page)
p.addPage(name, page)
}
}
}
return nil
}
func (p *Page) addPage(name string, page *Page) {
if p.pages == nil {
p.pages = map[string]*Page{}
}
p.pages[name] = page
}
// process processes the directory's contents.
func (p *Page) process(cfg *Site, task *Task) error {
// Build feeds before templates are applied to the page contents
@ -369,25 +379,30 @@ func execute(command []string, input io.Reader, output io.Writer) error {
return nil
}
func (p *Page) getPage(path string) *Page {
// XXX: This is inefficient
if p.Path == path {
// GetPage returns the page with the given path.
func (p *Page) GetPage(path string) *Page {
path = pathpkg.Clean(path)
if path == "." {
return p
}
for _, page := range p.Pages {
if page.FilePath == path {
return page
}
}
for _, dir := range p.Dirs {
if dir.Path == path {
return dir
}
}
for _, dir := range p.Dirs {
if page := dir.getPage(path); page != nil {
return page
}
}
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
if p.FilePath != "." && !strings.HasPrefix(path, p.FilePath) {
return nil
}
path = strings.TrimPrefix(path, p.FilePath)
if path == "" {
return p
}
path = strings.TrimPrefix(path, "/")
}
page := p
for _, part := range strings.Split(path, "/") {
page = page.pages[part]
if page == nil {
break
}
}
return page
}

View file

@ -125,7 +125,3 @@ func LoadSite(config string) (*Site, error) {
return site, nil
}
func (s *Site) page(path string) *Page {
return s.Root.getPage(path)
}