Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Created December 21, 2019 17:42
Show Gist options
  • Save StevenACoffman/326b1dbcfc05d206500c186112e788ab to your computer and use it in GitHub Desktop.
Save StevenACoffman/326b1dbcfc05d206500c186112e788ab to your computer and use it in GitHub Desktop.
Template tricks
package main
import (
"bytes"
"fmt"
"text/template"
)
func WithMap(format string, m map[string]string) (string, error) {
tpl, err := template.New("format").Parse(format)
if err != nil {
return "", err
}
var buf bytes.Buffer
err = tpl.Execute(&buf, m)
if err != nil {
return "", err
}
return buf.String(), nil
}
func main() {
m := map[string]string{
"data": "world",
"end": "!",
}
f, err := WithMap("Hello {{.data}}{{.end}}", m)
if err != nil {
panic(err)
}
fmt.Println(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment