Golang模板范围中的最后一项 [英] Last item in a Golang template range

查看:125
本文介绍了Golang模板范围中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定模板

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

这可以输出

 一,二,三



但是,如果要输出

 一,二和三

我需要知道哪个是上述范围中的最后一个元素。

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



检测模板范围内的最后一个值是否可能?欢迎。

解决方案

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



http://play.golang.org/p/MT91mLqk1

 包主

导入(
os
反映
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 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


cf




Given the template

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

This can output

one, two, three

If, however, I want to output

one, two, and three

I'd need to know which is the last element in the range above.

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)
}

Note: You can also do it without reflect using the len function (credit to Russ Cox): http://play.golang.org/p/V94BPN0uKD

c.f.

这篇关于Golang模板范围中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆