2
{{$Total := 0.00}}
{{ range .Shoes }}
  {{ if .Quantity }}
    {{ $Total := add $Total (mul .Price .Quantity)}}
  {{ end }}
{{ end }}
{{printf "%.2f" $Total}}

function "add" not defined

Total price * Quantity = Final Price

Kelvin Ng
  • 21
  • 4
  • 2
    Neither `add` nor `mul`. See https://pkg.go.dev/text/template@go1.20#hdr-Functions for a list of included functions. To add custom functions use https://pkg.go.dev/text/template@go1.20#FuncMap. – mkopriva Feb 09 '23 at 03:40

1 Answers1

3
package main

import (
    "bytes"
    "fmt"
    "text/template"
)

func add(total, prod float64) float64 {
    return total + prod
}
func mul(quantity, price float64) float64 {
    return quantity * price
}

var funcMap = template.FuncMap{
    "add": add,
    "mul": mul,
}

func main() {
    t := template.Must(template.New("test").Funcs(funcMap).Parse(tmpl))
    var tpl bytes.Buffer
    b := TMPL{
        Shoes: []Shoe{
            Shoe{
                5,
                20,
            },
        },
    }
    err := t.Execute(&tpl, &b)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(tpl.String())
}

type TMPL struct {
    Total int
    Shoes []Shoe
}

type Shoe struct {
    Quantity float64
    Price    float64
}

var tmpl = `{{$Total := 0.00}}
{{ range .Shoes }}
  {{ if .Quantity }}
    {{ $Total = (add $Total (mul .Price .Quantity))}}
  {{ end }}
{{ end }}
{{printf "%.2f" $Total}}

playground