1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-11-30 08:08:59 +01:00
gojekyll/renderers/layouts.go

88 lines
2.0 KiB
Go
Raw Normal View History

2017-08-18 17:07:01 +02:00
package renderers
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/osteele/gojekyll/frontmatter"
2017-07-24 14:09:14 +02:00
"github.com/osteele/gojekyll/templates"
"github.com/osteele/gojekyll/utils"
2017-06-29 13:27:43 +02:00
"github.com/osteele/liquid"
)
2017-08-22 16:47:34 +02:00
// ApplyLayout applies the named layout to the content.
func (p *Manager) ApplyLayout(name string, content []byte, vars liquid.Bindings) ([]byte, error) {
2017-07-24 14:09:14 +02:00
for name != "" {
var lfm map[string]interface{}
tpl, err := p.FindLayout(name, &lfm)
if err != nil {
return nil, err
}
2017-08-10 16:44:04 +02:00
b := utils.MergeStringMaps(vars, map[string]interface{}{
2017-08-22 16:47:34 +02:00
"content": string(content),
2017-07-24 14:09:14 +02:00
"layout": lfm,
})
2017-08-22 16:47:34 +02:00
content, err = tpl.Render(b)
2017-07-24 14:09:14 +02:00
if err != nil {
return nil, utils.WrapPathError(err, name)
}
name = templates.VariableMap(lfm).String("layout", "")
}
2017-08-22 16:47:34 +02:00
return content, nil
2017-07-24 14:09:14 +02:00
}
// FindLayout returns a template for the named layout.
2017-09-02 18:10:35 +02:00
func (p *Manager) FindLayout(base string, fmp *map[string]interface{}) (tpl *liquid.Template, err error) {
2017-07-14 18:12:25 +02:00
// not cached, but the time here is negligible
exts := []string{"", ".html"}
2017-07-24 14:18:05 +02:00
for _, ext := range strings.SplitN(p.cfg.MarkdownExt, `,`, -1) {
exts = append(exts, "."+ext)
}
var (
2017-07-01 03:06:12 +02:00
filename string
content []byte
found bool
)
2017-07-24 14:09:14 +02:00
loop:
for _, dir := range p.layoutDirs() {
for _, ext := range exts {
filename = filepath.Join(dir, base+ext)
2023-03-03 21:58:41 +01:00
content, err = os.ReadFile(filename)
2017-07-24 14:09:14 +02:00
if err == nil {
found = true
break loop
}
if !os.IsNotExist(err) {
return nil, err
}
}
}
if !found {
return nil, fmt.Errorf("no template for %s", base)
}
lineNo := 1
2017-09-02 18:10:35 +02:00
fm, err := frontmatter.Read(&content, &lineNo)
if err != nil {
return
}
2017-09-02 18:10:35 +02:00
if fmp != nil {
*fmp = fm
}
tpl, err = p.liquidEngine.ParseTemplateLocation(content, filename, lineNo)
2017-07-04 23:13:47 +02:00
if err != nil {
return nil, err
}
return
2017-06-24 19:30:01 +02:00
}
// LayoutsDir returns the path to the layouts directory.
2017-08-18 17:07:01 +02:00
func (p *Manager) layoutDirs() []string {
2017-08-10 16:44:04 +02:00
dirs := []string{filepath.Join(p.sourceDir(), p.cfg.LayoutsDir)}
2017-07-24 14:09:14 +02:00
if p.ThemeDir != "" {
dirs = append(dirs, filepath.Join(p.ThemeDir, "_layouts"))
}
return dirs
}