Go模板表达式

标签 go

{{$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}}

playground

关于Go模板表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75393914/

相关文章:

multithreading - 在 Go 中,如果您写入封闭 channel 会发生什么?我可以将 channel 视为确定性 RE 销毁吗?

docker - 在 GoLang Docker SDK 中为卷定义挂载点

pointers - panic : runtime error: invalid memory address or nil pointer dereference

go - 如何添加新路由来自动生成资源?

file - 打开和写入文件时出错

go - “invalid recursive type”和“illegal cycle in declaration of”

file - Gorilla Golang Pathprefix 不提供文件

go - 从 YAML 对象列表创建 API 对象

go - 如何使用 golang 中的 api 编辑 GCP 云存储中的现有数据

nginx - 如何使用 Auth0 设置 Nginx?