模板范围内的最后一项 [英] Last item in a template range
问题描述
给出模板:
{{range $i, $e := .SomeField}}
{{if $i}}, {{end}}
$e.TheString
{{end}}
这可以输出:
one, two, three
但是,如果我想输出:
one, two, and three
我需要知道上面范围内的最后一个元素.
I'd need to know which is the last element in the range above.
我可以设置一个变量,该变量保存数组 .SomeField
的长度,但是始终为3,并且上面的 $ i
值将永远变为2.而且,根据我所见,您无法在模板中执行算术运算.
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)
}
注意:您还可以使用 len
函数(贷记给Russ Cox)在不反射的情况下执行此操作: http://play.golang.org/p/V94BPN0uKD
Note: You can also do it without reflect using the len
function (credit to Russ Cox):
http://play.golang.org/p/V94BPN0uKD
c.f.
- https://groups.google.com/forum/#!topic/golang-nuts/yRXHSCjVAcM
- https://groups.google.com/论坛/#!msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ
- https://groups.google.com/forum/#!topic/golang-nuts/mqRbR7AFJj0
这篇关于模板范围内的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!