{{$Total := 0.00}}
{{ range .Shoes }}
{{ if .Quantity }}
{{ $Total := add $Total (mul .Price .Quantity)}}
{{ end }}
{{ end }}
{{printf "%.2f" $Total}}
函数“add”未定义
总价*数量=最终价格
最佳答案
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}}
关于Go模板表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75393914/