From 7e87d0967987dab547d954010d184f36b43076a9 Mon Sep 17 00:00:00 2001 From: William Albertus Dembo <29192168+walbertus@users.noreply.github.com> Date: Wed, 12 Jan 2022 14:08:12 +0700 Subject: [PATCH] feat: add iterator function to template execution Co-authored-by: Eko Simanjuntak Co-authored-by: Rizky Putra --- pkg/tmpl/result.go | 23 +++++++++++++++++++++++ pkg/tmpl/scan.go | 12 ++---------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/pkg/tmpl/result.go b/pkg/tmpl/result.go index c785cdc..7b9e367 100644 --- a/pkg/tmpl/result.go +++ b/pkg/tmpl/result.go @@ -219,3 +219,26 @@ func (result *scanResult) Execute(data interface{}) (mapResult map[string]string return } +func (result *scanResult) addInternalFunction() { + result.template.Funcs(template.FuncMap{ + "Iterate": func(count *uint) []uint { + var counter uint + var items []uint + for counter = 0; counter < (*count); counter++ { + items = append(items, counter) + } + return items + }, + }) +} + +func NewScanResult(rootPath string, template *template.Template, templateMap FileMap, option *ScanOption) ScanResult { + result := &scanResult{ + rootPath: rootPath, + template: template, + templateMap: templateMap, + option: option, + } + result.addInternalFunction() + return result +} diff --git a/pkg/tmpl/scan.go b/pkg/tmpl/scan.go index eba86d2..8a20c5a 100644 --- a/pkg/tmpl/scan.go +++ b/pkg/tmpl/scan.go @@ -92,12 +92,6 @@ func TemplateScanOption(scanPath string, option *ScanOption) (ScanResult, error) rootTemplate = rootTemplate.Delims(option.StartDelim, option.EndDelim) } - result := &scanResult{ - rootPath: scanPath, - template: rootTemplate, - option: option, - } - // start directory walk templateMap := FileMap{} err := filepath.Walk(scanPath, func(path string, info os.FileInfo, err error) error { @@ -124,7 +118,7 @@ func TemplateScanOption(scanPath string, option *ScanOption) (ScanResult, error) } // initiate new template with path as name - innerTemplate := result.template.New(relativePath).Funcs(sprig.TxtFuncMap()) + innerTemplate := rootTemplate.New(relativePath).Funcs(sprig.TxtFuncMap()) // parse template _, err = innerTemplate.Parse(string(byteArray)) @@ -138,9 +132,7 @@ func TemplateScanOption(scanPath string, option *ScanOption) (ScanResult, error) return nil }) - - result.templateMap = templateMap - + result := NewScanResult(scanPath, rootTemplate, templateMap, option) return result, err }