From 16347242608df70d23327ef752a9b67e230f6578 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Wed, 27 Dec 2023 19:38:59 -0800 Subject: [PATCH] Add MustGetTemplate and ExecuteTemplate functions --- namespace.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/namespace.go b/namespace.go index ad01e29..e40e21a 100644 --- a/namespace.go +++ b/namespace.go @@ -1,6 +1,10 @@ package salix -import "sync" +import ( + "fmt" + "io" + "sync" +) // Namespace represents a collection of templates that can include each other type Namespace struct { @@ -80,6 +84,25 @@ func (n *Namespace) GetTemplate(name string) (Template, bool) { 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 func (n *Namespace) getVar(name string) (any, bool) { n.mu.Lock()