From 2e0da5726b4e1c82e65691444010f45cacdd07a3 Mon Sep 17 00:00:00 2001 From: tenntenn Date: Fri, 12 Nov 2021 11:26:35 +0900 Subject: [PATCH] Add TemplateOption --- template.go | 61 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/template.go b/template.go index ad2ebd3..66f2224 100644 --- a/template.go +++ b/template.go @@ -11,9 +11,44 @@ import ( "golang.org/x/tools/txtar" ) +// DefaultFuncMap is a default functions which using in a template. +var DefaultFuncMap = template.FuncMap{ + "gitkeep": func() string { + return ".gitkeep" + }, + "gomod": func() string { + return "go.mod" + }, + "gomodinit": func(path string) string { + f, err := ModInit(path) + if err != nil { + panic(err) + } + return f + }, +} + +// TemplateOption is an option for a template. +// It can decorate the template. +type TemplateOption func(*template.Template) (*template.Template, error) + +// TemplateWithFuncs add funcs to a template. +func TemplateWithFuncs(funcs template.FuncMap) TemplateOption { + return func(tmpl *template.Template) (*template.Template, error) { + return tmpl.Funcs(funcs), nil + } +} + +// TemplateWithDelims sets delims of a template. +func TemplateWithDelims(left, right string) TemplateOption { + return func(tmpl *template.Template) (*template.Template, error) { + return tmpl.Delims(left, right), nil + } +} + // ParseTemplate parses a template which represents as txtar format from given a file system. // The name is template name. If stripPrefix is not empty string, ParseTemplate uses sub directory of stripPrefix. -func ParseTemplate(tmplFS fs.FS, name, stripPrefix string) (*template.Template, error) { +func ParseTemplate(tmplFS fs.FS, name, stripPrefix string, options ...TemplateOption) (*template.Template, error) { fsys := tmplFS if stripPrefix != "" { var err error @@ -28,21 +63,15 @@ func ParseTemplate(tmplFS fs.FS, name, stripPrefix string) (*template.Template, return nil, err } - return template.New(name).Delims("@@", "@@").Funcs(template.FuncMap{ - "gitkeep": func() string { - return ".gitkeep" - }, - "gomod": func() string { - return "go.mod" - }, - "gomodinit": func(path string) string { - f, err := ModInit(path) - if err != nil { - panic(err) - } - return f - }, - }).Parse(string(txtar.Format(ar))) + tmpl := template.New(name).Delims("@@", "@@").Funcs(DefaultFuncMap) + for _, opt := range options { + tmpl, err = opt(tmpl) + if err != nil { + return nil, err + } + } + + return tmpl.Parse(string(txtar.Format(ar))) } // ExecuteTemplate executes a template with data.