Go模板删除范围循环中的最后一个逗号

问题描述 投票:5回答:2

我有这样的代码:

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

它将输出:

key:一个值:b,key:c value:d,

但是我想要这样的东西:

key:值:b,键:c值:d

我不需要最后一个逗号,如何删除它。我在这里找到了一个循环数组的解决方案:https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ,但是我无法获得地图的索引。

go go-templates
2个回答
6
投票

以下是使用模板函数编写逗号分隔的键值对的方法。

声明一个函数,该函数返回一个递增并返回计数器的函数:

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

在模板中使用它,如下所示:

    {{$c := counter}}{{range $key, $value := $}}{{if call $c}}, {{end}}key:{{$key}} value:{{$value}}{{end}}

此模板在键对之前写入分隔符,而不是在对之后。

计数器在循环之前创建,并在每次迭代循环时递增。第一次循环时不写入分隔符。

Run it in the playground.


3
投票

自从去1.11 it is now possible to change values of template variables。这使我们可以在不需要自定义函数(在模板之外)的情况下执行此操作。

以下模板执行此操作:

{{$first := true}}
{{range $key, $value := $}}
    {{if $first}}
        {{$first = false}}
    {{else}}
        ,
    {{end}}
    key:{{$key}} value:{{$value}}
{{end}}

以下是问题中改变的工作示例:

type Map map[string]string
m := Map{
    "a": "b",
    "c": "d",
    "e": "f",
}
const temp = `{{$first := true}}{{range $key, $value := $}}{{if $first}}{{$first = false}}{{else}}, {{end}}key:{{$key}} value:{{$value}}{{end}}`
t := template.Must(template.New("example").Parse(temp))
t.Execute(os.Stdout, m)

哪些输出(在Go Playground上试试):

key:a value:b, key:c value:d, key:e value:f
© www.soinside.com 2019 - 2024. All rights reserved.