我有这样的代码:
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)
}
它会输出:
键:值:b,键:c值:d,
但我想要这样的事情:
键:值:b,键:c值:d
我不需要最后一个逗号,如何删除它。我在这里找到了一个循环数组的解决方案:https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ,但是我无法获得地图的索引。
答案 0 :(得分: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}}
此模板在键对之前写入分隔符,而不是在对之后。
计数器在循环之前创建,并在每次迭代循环时递增。第一次循环时不会写入分隔符。
答案 1 :(得分:1)
自Go 1.11 it is now possible to change values of template variables开始。这使我们可以不需要自定义功能(不在模板中)执行此操作。
以下模板可以做到这一点:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/opencv/core/Core
at headsupdisplay.Main.main(Main.java:457)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.opencv.core.Core
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 12 more
Exception running application headsupdisplay.Main
这是问题中更改后的工作示例:
{{$first := true}}
{{range $key, $value := $}}
{{if $first}}
{{$first = false}}
{{else}}
,
{{end}}
key:{{$key}} value:{{$value}}
{{end}}
哪个输出(在Go Playground上尝试):
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)