oh-my-posh/src/template.go

35 lines
710 B
Go
Raw Normal View History

2021-02-07 01:54:36 -08:00
package main
import (
"bytes"
2021-04-11 06:24:03 -07:00
"errors"
2021-02-07 01:54:36 -08:00
"text/template"
"github.com/Masterminds/sprig"
2021-02-07 01:54:36 -08:00
)
const (
// Errors to show when the template handling fails
invalidTemplate = "invalid template text"
incorrectTemplate = "unable to create text based on template"
)
type textTemplate struct {
Template string
Context interface{}
}
2021-04-11 06:24:03 -07:00
func (t *textTemplate) render() (string, error) {
tmpl, err := template.New("title").Funcs(sprig.TxtFuncMap()).Parse(t.Template)
2021-02-07 01:54:36 -08:00
if err != nil {
2021-04-11 06:24:03 -07:00
return "", errors.New(invalidTemplate)
2021-02-07 01:54:36 -08:00
}
buffer := new(bytes.Buffer)
defer buffer.Reset()
err = tmpl.Execute(buffer, t.Context)
if err != nil {
2021-04-11 06:24:03 -07:00
return "", errors.New(incorrectTemplate)
2021-02-07 01:54:36 -08:00
}
2021-04-11 06:24:03 -07:00
return buffer.String(), nil
2021-02-07 01:54:36 -08:00
}