diff --git a/funcs.go b/funcs.go index 0c9c63c..2704ebe 100644 --- a/funcs.go +++ b/funcs.go @@ -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, diff --git a/page.go b/page.go index 9a9084f..d631b96 100644 --- a/page.go +++ b/page.go @@ -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 + 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 } } - 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 - } - } - return nil + return page } diff --git a/site.go b/site.go index bbb31dd..9524d30 100644 --- a/site.go +++ b/site.go @@ -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) -}