Skip to content

Instantly share code, notes, and snippets.

@dwburke
Last active January 18, 2021 15:19
Show Gist options
  • Save dwburke/2444ca15175771996e689906d7312601 to your computer and use it in GitHub Desktop.
Save dwburke/2444ca15175771996e689906d7312601 to your computer and use it in GitHub Desktop.
printf using template vars... I found this a while back on stackoverflow or somewhere like that... original call is commented, just using an interface was more flexible for my uses
package util
import (
"bytes"
"text/template"
)
// Example:
// str := Tprintf("{{ .Thing }} a thing a do foo, bar", data)
// You may or may not want to change it to return or do more with any error
// Tprintf passed template string is formatted usign its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
//func Tprintf(tmpl string, data map[string]interface{}) string {
func Tprintf(tmpl string, data interface{}) string {
t := template.Must(template.New("tprintf").Parse(tmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
return ""
}
return buf.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment