【问题标题】:nest if condition within a range in golang templates在golang模板的范围内嵌套if条件
【发布时间】:2017-04-11 04:53:57
【问题描述】:

如何在 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

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    如果你从Execute返回check the error,你会发现模板正试图将参数传递给非函数$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

    【讨论】:

    • 谢谢。当我浏览文档时,我错过了整个前缀部分:)
    猜你喜欢
    • 2017-11-30
    • 2021-09-14
    • 2016-11-06
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2011-03-19
    相关资源
    最近更新 更多