Golang模板范围中的最后一项 [英] Last item in a Golang template range
问题描述
给定模板
{{range $ i,$ e:= .SomeField}}
{{如果$ i}},{{end}}
$ e.TheString
{{end}}
这可以输出
一,二,三
但是,如果要输出
一,二和三
我需要知道哪个是上述范围中的最后一个元素。
我可以设置一个变量来保存数组.SomeField的长度,但它总是3,而上面的$ i值只会达到2 。你不能在我看到的模板中执行算术运算。
检测模板范围内的最后一个值是否可能?欢迎。
解决方案这可能不是最优雅的解决方案,但它是我能找到的最好的解决方案:
http://play.golang.org/p/MT91mLqk1
包主
导入(
os
反映
text / template
)
var fns = template.FuncMap {
last:func(x int,a interface {})bool {
return x == reflect.ValueOf(a).Len() - 1
},
}
func main(){
t:= template.Must(template.New(abc)。Funcs(fns).Parse(`{{range $ i,$ e:=。}} {{if $ i}},{{end}}} ){{if if last $ i $}} and {{end}} {{$ e}} {{end}}。))
a:= [] string {one,two,three }
t.Execute(os.Stdout,a)
}
使用
len
函数(放在Russ Cox中):
http://play.golang.org/p/V94BPN0uKD
cf
- https://groups.google.com/forum/#!topic/golang-nuts/yRXHSCjVAcM
- / a>
- https:/ /groups.google.com/forum/#!topic/golang-nuts/mqRbR7AFJj0
Given the template
{{range $i, $e := .SomeField}} {{if $i}}, {{end}} $e.TheString {{end}}
This can output
one, two, three
If, however, I want to output
one, two, and three
I'd need to know which is the last element in the range above.
I can set a variable that holds the length of the array .SomeField, but that will always be 3, and the $i value above will only ever get to 2. And you can't perform arithmetic in templates from what I've seen.
Is detecting the last value in a template range possible? Cheers.
解决方案This is probably not the most elegant solution but it's the best I could find:
http://play.golang.org/p/MT91mLqk1s
package main import ( "os" "reflect" "text/template" ) var fns = template.FuncMap{ "last": func(x int, a interface{}) bool { return x == reflect.ValueOf(a).Len() - 1 }, } func main() { t := template.Must(template.New("abc").Funcs(fns).Parse(`{{range $i, $e := .}}{{if $i}}, {{end}}{{if last $i $}}and {{end}}{{$e}}{{end}}.`)) a := []string{"one", "two", "three"} t.Execute(os.Stdout, a) }
Note: You can also do it without reflect using the
len
function (credit to Russ Cox): http://play.golang.org/p/V94BPN0uKDc.f.
- https://groups.google.com/forum/#!topic/golang-nuts/yRXHSCjVAcM
- https://groups.google.com/forum/#!msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ
- https://groups.google.com/forum/#!topic/golang-nuts/mqRbR7AFJj0
这篇关于Golang模板范围中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文