mirror of
https://github.com/SAP/jenkins-library.git
synced 2024-12-14 11:03:09 +02:00
31 lines
1.0 KiB
Go
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
|
|
}
|