1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-11-27 03:34:46 +01:00
gojekyll/renderers/layouts.go

86 lines
2.0 KiB
Go
Raw Normal View History

2017-08-18 17:07:01 +02:00
package renderers
import (
"fmt"
"io/ioutil"
"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-07-24 14:09:14 +02:00
// ApplyLayout applies the named layout to the data.
2017-08-18 17:07:01 +02:00
func (p *Manager) ApplyLayout(name string, data []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-07-24 14:09:14 +02:00
"content": string(data),
"layout": lfm,
})
data, err = tpl.Render(b)
if err != nil {
return nil, utils.WrapPathError(err, name)
}
name = templates.VariableMap(lfm).String("layout", "")
}
return data, nil
}
// FindLayout returns a template for the named layout.
2017-08-18 17:07:01 +02:00
func (p *Manager) FindLayout(base string, fm *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)
content, err = ioutil.ReadFile(filename)
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
*fm, err = frontmatter.Read(&content, &lineNo)
if err != nil {
return
}
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
}