Skip to content

Commit

Permalink
Merge pull request #1 from gostaticanalysis/add-tempalte-options
Browse files Browse the repository at this point in the history
Add TemplateOption
  • Loading branch information
tenntenn authored Nov 12, 2021
2 parents 244b0ed + 2e0da57 commit c529796
Showing 1 changed file with 45 additions and 16 deletions.
61 changes: 45 additions & 16 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down

0 comments on commit c529796

Please sign in to comment.