github.com/jaylevin/jenkins-library@v1.230.4/pkg/piperutils/templateUtils.go (about)

     1  package piperutils
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"text/template"
     7  )
     8  
     9  // ExecuteTemplate parses the provided template, substitutes values and returns the output
    10  func ExecuteTemplate(txtTemplate string, context interface{}) (string, error) {
    11  	return ExecuteTemplateFunctions(txtTemplate, nil, context)
    12  }
    13  
    14  // ExecuteTemplateFunctions parses the provided template, applies the transformation functions, substitutes values and returns the output
    15  func ExecuteTemplateFunctions(txtTemplate string, functionMap template.FuncMap, context interface{}) (string, error) {
    16  	template := template.New("tmp")
    17  	if functionMap != nil {
    18  		template = template.Funcs(functionMap)
    19  	}
    20  	template, err := template.Parse(txtTemplate)
    21  	if err != nil {
    22  		return "<nil>", fmt.Errorf("Failed to parse template definition %v: %w", txtTemplate, err)
    23  	}
    24  	var output bytes.Buffer
    25  	err = template.Execute(&output, context)
    26  	if err != nil {
    27  		return "<nil>", fmt.Errorf("Failed to transform template definition %v: %w", txtTemplate, err)
    28  	}
    29  	return output.String(), nil
    30  }