Add MustGetTemplate and ExecuteTemplate functions

This commit is contained in:
Elara 2023-12-27 19:38:59 -08:00
parent b6c177c3d2
commit 1634724260

View File

@ -1,6 +1,10 @@
package salix package salix
import "sync" import (
"fmt"
"io"
"sync"
)
// Namespace represents a collection of templates that can include each other // Namespace represents a collection of templates that can include each other
type Namespace struct { type Namespace struct {
@ -80,6 +84,25 @@ func (n *Namespace) GetTemplate(name string) (Template, bool) {
return t, ok return t, ok
} }
// MustGetTemplate is the same as GetTemplate but it panics if the template
// doesn't exist in the namespace.
func (n *Namespace) MustGetTemplate(name string) Template {
tmpl, ok := n.GetTemplate(name)
if !ok {
panic(fmt.Errorf("no such template: %q", name))
}
return tmpl
}
// ExecuteTemplate gets and executes a template with the given name.
func (n *Namespace) ExecuteTemplate(w io.Writer, name string, vars map[string]any) error {
tmpl, ok := n.GetTemplate(name)
if !ok {
return fmt.Errorf("no such template: %q", name)
}
return tmpl.WithVarMap(vars).Execute(w)
}
// getVar tries to get a variable from the namespace's variable map // getVar tries to get a variable from the namespace's variable map
func (n *Namespace) getVar(name string) (any, bool) { func (n *Namespace) getVar(name string) (any, bool) {
n.mu.Lock() n.mu.Lock()