去模板删除范围循环中的最后一个逗号 [英] Go template remove the last comma in range loop
问题描述
我有这样的代码:
package main
import (
"text/template"
"os"
)
func main() {
type Map map[string]string
m := Map {
"a": "b",
"c": "d",
}
const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}`
t := template.Must(template.New("example").Parse(temp))
t.Execute(os.Stdout, m)
}
它将输出:
键:a值:b,键:c值:d,
key:a value:b,key:c value:d,
但是我想要这样的东西:
but I want something like this:
键:a值:b,键:c值:d
key:a value:b,key:c value:d
我不需要最后一个逗号,如何删除它.我在这里找到了用于循环数组的解决方案: https://groups .google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ ,但我无法获取地图索引.
I don't need the last comma, how to remove it. I found a solution for looping an array here: https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ , but I can't get index for a map.
推荐答案
以下是使用模板函数编写逗号分隔的键/值对的方法.
Here's how to write comma separated key-value pairs using a template function.
声明一个函数,该函数返回一个递增并返回计数器的函数:
Declare a function that returns a function that increments and returns a counter:
func counter() func() int {
i := -1
return func() int {
i++
return i
}
}
将此功能添加到模板:
t := template.Must(template.New("example").Funcs(template.FuncMap{"counter": counter}).Parse(temp))
像这样在模板中使用它:
Use it in the template like this:
{{$c := counter}}{{range $key, $value := $}}{{if call $c}}, {{end}}key:{{$key}} value:{{$value}}{{end}}
此模板将分隔符写在键值对之前,而不是写在对之后.
This template writes the separators before the key-value pairs instead after the pairs.
计数器在循环之前创建,并在每次循环中递增.分隔符不会在循环中第一次写入.
The counter is created before the loop and incremented on each iteration through the loop. The separator is not written the first time through the loop.
可以通过将if语句移至Go代码来简化模板中的逻辑:
The logic in the template can be simplified by moving the if statement to Go code:
func separator(s string) func() string {
i := -1
return func() string {
i++
if i == 0 {
return ""
}
return s
}
}
将功能添加到模板:
t := template.Must(template.New("example").Funcs(template.FuncMap{"separator": separator}).Parse(temp))
像这样使用它:
{{$s := separator ", "}}{{range $key, $value := $}}{{call $s}}key:{{$key}} value:{{$value}}{{end}}
这篇关于去模板删除范围循环中的最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!