英文:
Go template expression
问题
{{$Total := 0.00}}
{{ range .Shoes }}
{{ if .Quantity }}
{{ $Total := add $Total (mul .Price .Quantity)}}
{{ end }}
{{ end }}
{{printf "%.2f" $Total}}
函数"add"未定义
总价 * 数量 = 最终价格
英文:
{{$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
答案1
得分: 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{
Total: 0,
Shoes: []Shoe{
Shoe{
Quantity: 5,
Price: 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}}
以上是你提供的代码的翻译结果。
<details>
<summary>英文:</summary>
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][1]
[1]: https://go.dev/play/p/RZ_qkM3pyBX
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论