diff --git a/pkg/template/include.go b/pkg/template/include.go index 388fc5e..d934c63 100644 --- a/pkg/template/include.go +++ b/pkg/template/include.go @@ -5,10 +5,14 @@ import ( "io" ) +// Template defines the interface which expects the ExecuteTemplate function +// to be defined, so it can be used by the include function. type Template interface { ExecuteTemplate(io.Writer, string, any) error } +// Returns the function map defining the include template function. Which allows +// to call defined templates from within a template. func IncludeFunc(tpl Template) map[string]any { return map[string]any{ "include": func(name string, data any) (string, error) { diff --git a/pkg/template/include_test.go b/pkg/template/include_test.go new file mode 100644 index 0000000..de9578d --- /dev/null +++ b/pkg/template/include_test.go @@ -0,0 +1,60 @@ +package template + +import ( + htmlTemplate "html/template" + "strings" + "testing" + textTemplate "text/template" +) + +var ( + validTemplate = ` +{{- define "test" -}} +{{ . }} +{{- end -}} +{{ include "test" "abc" -}} +` + invalidTemplate = `{{ include "test" "abc" }}` +) + +func TestWithValidTemplate(t *testing.T) { + tp := htmlTemplate.New("testValid") + tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(validTemplate) + if err != nil { + t.Errorf("Error parsing template %q", err) + } + var b strings.Builder + if err := tpl.Execute(&b, nil); err != nil { + t.Errorf("Error executing template %q", err) + } + if b.String() != "abc" { + t.Errorf("Expecting output to be %q, got %q", "abc", b.String()) + } +} + +func TestWithATextTemplate(t *testing.T) { + tp := textTemplate.New("testValid") + tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(validTemplate) + if err != nil { + t.Errorf("Error parsing template %q", err) + } + var b strings.Builder + if err := tpl.Execute(&b, nil); err != nil { + t.Errorf("Error executing template %q", err) + } + if b.String() != "abc" { + t.Errorf("Expecting output to be %q, got %q", "abc", b.String()) + } +} + +func TestWithAnInvalidTemplate(t *testing.T) { + tp := textTemplate.New("testInvalid") + tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(invalidTemplate) + if err != nil { + t.Errorf("Error parsing template %q", err) + } + var b strings.Builder + if err := tpl.Execute(&b, nil); err == nil { + t.Error("Expecting error, got nothing") + } +}