go - 模板范围中的最后一项

标签 go go-templates

给定模板:

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

这可以输出:

one, two, three

但是,如果我想输出:

one, two, and three

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

我可以设置一个变量来保存数组 .SomeField 的长度,但它始终为 3,并且上面的 $i 值只会达到2. 根据我所见,您无法在模板中执行算术运算。

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

最佳答案

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

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

c.f.

关于go - 模板范围中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367337/

相关文章:

python - 在 Mac Os 中编译和链接 Python 模块

go - 通过 API GW 调用时,AWS Lambda Go 函数未获取请求正文

regex - 验证图像的正则表达式

json - 我可以使用 MarshalJSON 将任意字段添加到 golang 中的 json 编码吗?

转到模板 : can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)

templates - 在Go模板中按名称访问结构成员

go - 这个类型声明是什么意思?

戈兰 : Custom template "block" functions?

go - 占位符不被替换

json - 加入引号、逗号分隔的字符串(给出包含这些字符串的结构列表)