I want to devide a number in my template by 1000, so I wrote:
fm := template.FuncMap{"divideBy1000": func(a int) float64 {
return a / 1000
}}
t, err := template.ParseFiles("order.html")
if err != nil {
panic(err)
}
var processed bytes.Buffer
err = t.ExecuteTemplate(&processed, "page", struct {
Sender string
PushName string
OLines global.OrderDetailData
}{
Sender: sender,
PushName: pushName,
OLines: oLines})
if err != nil {
panic(err)
}
outputPath := "./attachements/index.html"
f, err := os.Create(outputPath)
if err != nil {
panic(err)
}
w := bufio.NewWriter(f)
w.WriteString(processed.String())
w.Flush()
Any in my template I’ve:
{{define "page"}}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="x-apple-disable-message-reformatting">
<title>{{.Sender}}</title>
</head>
<body style="margin:0;padding:0;">
User: {{.PushName}}<br>
Mobiles:{{.Sender}}<br>
===========
<br>
Order id: {{.OLines.Order.ID}} <br>
Order date: {{.OLines.Order.CreationTs}}<br>
Order lines:<br>
===========
<br>
{{range .OLines.Order.Product}}
SKU Code: {{.RetailerID}} <br>
Name: {{.Name}} <br>
Qty: {{.Quantity}}
Price: {{.Price}} <br>
Currency: {{.Currency}} <br>
<a href={{.Image.URL}}>Link</a>
<br><br>
{{end}}<br>
=====================<br>
Approximate value: {{.OLines.Order.Price.Total}}<br>
Approximate value in Thousands: {{divideBy1000 .OLines.Order.Price.Total}}<br>
</body>
</html>
{{end}}
By my template is not executed because if the statement at the end of the template:
{{divideBy1000 .OLines.Order.Price.Total}}
Which means the function divideBy1000
is not defined, which is correct as I do not know how to attach my function fm
to the template:
fm := template.FuncMap{"divideBy1000": func(a int) float64 {
return a / 1000
}}
Any idea?