go - 如何计算 golang 模板中列的总数?

标签 go go-templates go-html-template

我在 html/模板中有这段代码:

{{ $TotalPrice := 0.0 }}
{{ range $i, $tx := .Transactions }}
{{ $TotalPrice := FloatInc $TotalPrice (StrToFloat .TotalPrice) }}
  <tr>
    <td>{{ inc $i 1 }}</td> 
    <td>{{ .Description.String }}</td>
    <td>{{ .Type }}</td>
    <td>{{ .TotalPrice }}</td>
    <td>{{ .Note }}</td>  
  </tr>  
{{ end }}
<tr>
  <td></td> 
  <td></td>
  <td></td>
  <td>{{ $TotalPrice }}</td>
  <td></td>
  <td></td>
</tr> 

交易是带有 TotalPrice 数据库字段的货币交易,我根据 Iris framework 有 4 个函数规范。

tmpl.AddFunc("dec", func(num int, step int) int {
    return num - step
})

tmpl.AddFunc("inc", func(num int, step int) int {
    return num + step
})

tmpl.AddFunc("FloatDec", func(num float64, step float64) float64 {
    return num - step
})

tmpl.AddFunc("FloatInc", func(num float64, step float64) float64 {
    return num + step
})

tmpl.AddFunc("StrToFloat", func(s string) (float64, error) {
    return strconv.ParseFloat(s, 64)
}) 

我注意到 $TotalPrice 为每次迭代保留初始值 (0.0),因此范围内的 {{ $TotalPrice }} 将打印 .TotalPrice 值,最后一行 $TotalPrice 的值也将是 0.0那么在 go 模板中,什么是等价的:

nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)

最佳答案

在 Go 的模板中,一旦你声明了一个变量并为其赋值,你就不能改变它的值。您的代码中发生的事情是:

  1. 声明为$TotalPrice := 0.0 的外部总价的值始终为0.0,并且变量范围扩展到模板的末尾。
  2. 当您在range 中定义了一个名为$TotalPrice 的变量时,尽管变量名相同,但会分配一个全新的变量。分配给该变量的值由 FloatInc($TotalPrice, .TotalPrice) 给出。请注意,参数 $TotalPrice 指的是外部总价,即 0.0,因此语句将等于 $TotalPrice := 0.0 + .TotalPrice .因此,当您在每次迭代中打印 $TotalPrice 时,您得到的是 current .TotalPrice 而不是累计总价。
  3. (2)中声明的变量范围在rangeend之间。因此,当您在最后一行打印 $TotalPrice 时,您得到的是 (1) 中声明的外部总价的值,即 0.0

在您的情况下,您需要声明一个以 Transactions 作为参数的函数,然后计算函数内部的总数,例如

tmpl.AddFunc("sum", func(transactions []Transaction) float64 {
    sum := 0.0
    for _, t := range transactions {
        if v, err := strconv.ParseFloat(t.TotalPrice, 64); err == nil {
            sum += v
        }
    }
    return sum
})

然后在模板中将其用作:

{{ $TotalPrice := sum .Transactions }}

关于go - 如何计算 golang 模板中列的总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929461/

相关文章:

macos - golang 1.16 cgo/clang 在 darwin/arm64 上构建失败

templates - 如何使用结构或变量值的字段作为模板名称?

Go Webapp 的 Dockerfile 目录结构

caching - Golang 多模板缓存

http - 服务器端相当于 ClientTrace 中的 go

mysql - 如何在golang中获取MySQL的BIT(64)

c++ - 加载C++库时出现“ undefined symbol ”

go - kubectl get with template string 失败,不兼容的类型进行比较

go - 将数据和变量传递到模板

提供静态文件时出现 golang 错误