Last item in a template range

前端 未结 2 722
一整个雨季
一整个雨季 2021-02-07 08:47

Given the template:

{{range $i, $e := .SomeField}}
        {{if $i}}, {{end}}
        $e.TheString
{{end}}

This can output:

one         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 09:30

    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/V94BPN0uKD

    c.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

提交回复
热议问题