Skip to content

Instantly share code, notes, and snippets.

@guilyx
Last active August 26, 2020 13:48
Show Gist options
  • Select an option

  • Save guilyx/82a5edf313230426f04185d7e87d247c to your computer and use it in GitHub Desktop.

Select an option

Save guilyx/82a5edf313230426f04185d7e87d247c to your computer and use it in GitHub Desktop.
Simple example showing how to extract a string variable out of a go template.
package main
import (
"text/template"
"fmt"
"bytes"
"time"
"strconv"
)
type Content struct {
LastName string
FirstName string
TestDate string
TestHour string
TestMinute string
}
func ResolveContentPlaceholders(contentTemplate Content, content string) (string, error) {
buf := new(bytes.Buffer)
t, err := template.New("content").Parse(content)
if err != nil {
return "", err
}
err = t.Execute(buf, contentTemplate)
if err != nil {
return "", err
}
return buf.String(), nil
}
func main() {
td := Content {
LastName: "Mariah",
FirstName: "Carrey",
TestDate: time.Now().Format("2006-01-02"),
TestHour: strconv.Itoa(time.Now().Hour()),
TestMinute: strconv.Itoa(time.Now().Minute()),
}
content := "Hey {{ .FirstName}}, hope everything's alright.\r\n I confirm you the exam is scheduled on {{ .TestDate}} at {{ .TestHour}}:{{ .TestMinute}}"
s, err := ResolveContentPlaceholders(td, content)
if err != nil {
fmt.Printf("Placeholders resolution failed: %s", err)
panic("haaaaaaaaaa!")
}
fmt.Println(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment