在Go语言模板中,如何在一个范围内嵌套if条件语句?

huangapple go评论82阅读模式
英文:

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)
}

在上述代码中,我们使用了Go语言的文本模板包(text/template)来执行模板渲染。模板字符串中的range语句用于迭代切片d中的元素。在每次迭代中,我们使用{{$i}}{{$v}}分别表示当前元素的索引和值。

在模板字符串中,我们使用了{{if $i gt 0}}条件语句来判断当前元素的索引是否大于0。如果满足条件,则输出一个逗号。这样可以在输出结果中,只在索引大于0的元素之间添加逗号。

最后,我们通过template.Must函数来解析和执行模板,并将结果输出到标准输出(os.Stdout)。

英文:

How to use an if condition within a range iteration loop in go?

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

答案1

得分: 3

如果你检查从Execute返回的错误,你会发现模板试图向非函数$i传递参数。正确的语法是:

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

参数跟在函数gt之后。函数gt不是中缀运算符

playground示例

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

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

playground示例

英文:

If you check the error returned from Execute, you will find that the template is attempting to pass arguments to the non-function $i. The correct syntax is:

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

The arguments follow the function gt. The function gt is not an infix operator.

playground example

If your goal is to print a comma separated list, then write it like this:

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

playground example

huangapple
  • 本文由 发表于 2017年4月11日 12:53:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/43337039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定