sms/template.go
2022-10-21 14:23:42 -07:00

88 lines
2.3 KiB
Go

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 = `
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Conversation: {{.Title}}</title>
<style type="text/css">
body { font-family: "Helvetica Neue", sans-serif; font-size: 10pt; }
p { margin: 0; clear: both; }
.time { text-align: center; color: #8e8e93; font-variant: small-caps; font-weight: bold; font-size: 9pt; }
.name { text-align: left; color: #8e8e93; font-size: 9pt; padding-left: 1ex; padding-top: 1ex; margin-bottom: 2px; }
img { max-width: 100%; }
.message { text-align: left; color: black; border-radius: 8px; background-color: #e1e1e1; padding: 6px; display: inline-block; max-width: 75%; margin-bottom: 5px; float: left; }
.message.sent { text-align: right; background-color: #007aff; color: white; float: right;}
</style>
</head>
<body>
{{- range $index, $msg := .Messages}}
{{- if newDate $index}}
<p class="time">{{$msg.Date}}</p><br />
{{end}}
{{- if $msg.Sent}}
<p class="message sent" title="{{$msg.Date}}">
{{else}}
<p class="name">{{$msg.Sender.Name}}</p>
<p class="message" title="{{$msg.Date}}">
{{ end}}
{{- range $index, $attachment := $msg.Attachments}}
<img title="{{$attachment.Name}}" src="data:{{$attachment.Mime}};base64,{{$attachment.Data | base64 }}"></img><br/>
{{end}}
{{- $msg.Text}}
</p><br />
{{end}}
</body>
</html>
`
// 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
}