Implement support for partial templates

This commit is contained in:
Adnan Maolood 2021-05-01 13:56:41 -04:00
parent 2409741e19
commit 6ec7b09c3a
2 changed files with 21 additions and 0 deletions

View file

@ -1,8 +1,10 @@
package main
import (
"fmt"
"os"
"path"
"strings"
"text/template"
"github.com/BurntSushi/toml"
@ -65,6 +67,17 @@ func (c *Config) LoadTemplates(path string) error {
URLs: c.URLs,
}
},
"partial": func(name string, data interface{}) (interface{}, error) {
t, ok := c.Templates.FindPartial(name)
if !ok {
return "", fmt.Errorf("Error: partial %q not found", name)
}
var b strings.Builder
if err := t.Execute(&b, data); err != nil {
return "", err
}
return b.String(), nil
},
})
return c.Templates.Load(path)
}

View file

@ -67,3 +67,11 @@ func (t *Templates) FindTemplate(path string, tmpl string) (*template.Template,
// Failed to find template
return nil, false
}
// FindPartial returns the partial template of the given name.
func (t *Templates) FindPartial(name string) (*template.Template, bool) {
if t, ok := t.tmpls[pathpkg.Join("/_partials", name)]; ok {
return t, true
}
return nil, false
}