package main import ( "encoding/base64" "html/template" "os" "time" ) func tpl(msgs []Message) error { // First we create a FuncMap with which to register the function. funcMap := template.FuncMap{ // The name "title" is what the function will be called in the template text. "newDate": func(i int) bool { if i == 0 { return true } return msgs[i].Date.Sub(msgs[i-1].Date.Time) > time.Minute*30 }, "base64": func(data []byte) string { return base64.StdEncoding.EncodeToString(data) }, } const templateText = ` Conversation: {{.Title}} {{- range $index, $msg := .Messages}} {{- if newDate $index}}

{{$msg.Date}}


{{end}} {{- if $msg.Sent}}

{{else}}

{{$msg.Sender.Name}}

{{ end}} {{- range $index, $attachment := $msg.Attachments}}
{{end}} {{- $msg.Text}}


{{end}} ` // Create a template, add the function map, and parse the text. tmpl, err := template.New("smsMessage").Funcs(funcMap).Parse(templateText) if err != nil { return err } file, err := os.Create("untitled.html") if err != nil { return err } defer file.Close() // Run the template to verify the output. err = tmpl.Execute(file, struct { Title string Messages []Message }{Title: "testing", Messages: msgs}) if err != nil { return err } return nil }