Golang模板范围中的最后一项

new*_*our 9 go go-templates

鉴于模板

{{range $i, $e := .SomeField}}
        {{if $i}}, {{end}}
        $e.TheString
{{end}}
Run Code Online (Sandbox Code Playgroud)

这可以输出

one, two, three
Run Code Online (Sandbox Code Playgroud)

但是,如果我想输出

one, two, and three
Run Code Online (Sandbox Code Playgroud)

我需要知道哪个是上面范围内的最后一个元素.

我可以设置一个变量来保存数组的长度.SomeField,但是它总是3,而上面的$ i值只会变为2.你不能在我看到的模板中执行算术运算.

是否可以检测模板范围中的最后一个值?干杯.

Aeg*_*gis 14

这可能不是最优雅的解决方案,但它是我能找到的最好的解决方案:

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)
}
Run Code Online (Sandbox Code Playgroud)

注意:您也可以在不反映使用该len函数的情况下完成此操作(来自Russ Cox):http: //play.golang.org/p/V94BPN0uKD

比照