1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-12 10:55:20 +02:00
sap-jenkins-library/pkg/piperutils/templateUtils.go
2020-05-25 19:48:59 +02:00

31 lines
1.0 KiB
Go

package piperutils
import (
"bytes"
"fmt"
"text/template"
)
// ExecuteTemplate parses the provided template, substitutes values and returns the output
func ExecuteTemplate(txtTemplate string, context interface{}) (string, error) {
return ExecuteTemplateFunctions(txtTemplate, nil, context)
}
// ExecuteTemplateFunctions parses the provided template, applies the transformation functions, substitutes values and returns the output
func ExecuteTemplateFunctions(txtTemplate string, functionMap template.FuncMap, context interface{}) (string, error) {
template := template.New("tmp")
if functionMap != nil {
template = template.Funcs(functionMap)
}
template, err := template.Parse(txtTemplate)
if err != nil {
return "<nil>", fmt.Errorf("Failed to parse template defintion %v: %w", txtTemplate, err)
}
var output bytes.Buffer
err = template.Execute(&output, context)
if err != nil {
return "<nil>", fmt.Errorf("Failed to transform template defintion %v: %w", txtTemplate, err)
}
return output.String(), nil
}