加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang模板范围中的最后一项

发布时间:2020-12-16 19:26:23 所属栏目:大数据 来源:网络整理
导读:鉴于模板 {{range $i,$e := .SomeField}} {{if $i}},{{end}} $e.TheString{{end}} 这可以输出 one,two,three 但是,如果我想输出 one,and three 我需要知道哪个是上面范围内的最后一个元素. 我可以设置一个包含数组.SomeField长度的变量,但总是3,而上面的$i值
鉴于模板
{{range $i,$e := .SomeField}}
        {{if $i}},{{end}}
        $e.TheString
{{end}}

这可以输出

one,two,three

但是,如果我想输出

one,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.

> 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读