如果条件在 golang 模板中的范围内嵌套

nest if condition within a range in golang templates

如何在 go 的范围迭代循环中使用 if 条件?

package main

import "os"
import "text/template"

const t = `{{range $i, $v := .}}{{$i}} {{$v}}{{if $i gt 0}}, {{end}}
{{end}}
`

func main() {
    d := []string{"a", "b", "c"}
    template.Must(template.New("").Parse(t)).Execute(os.Stdout, d)
}

https://play.golang.org/p/IeenD90FRM

如果您 check the errorExecute 返回,您会发现模板试图将参数传递给非函数 $i。正确的语法是:

const t = `{{range $i, $v := .}}{{$i}} {{$v}}{{if gt $i 0}}, {{end}}
{{end}}
`

参数跟在函数后面gt。函数 gt 不是 infix operator.

playground example

如果你的目标是打印一个逗号分隔的列表,那么这样写:

const t = `{{range $i, $v := .}}{{if $i}}, 
{{end}}{{$i}} {{$v}}{{end}}
`

playground example