我有以下代码(使用text/template):
inventory := map[string]string{"name of the movie": "hello"}
tmpl, err := template.New("test").Parse("Movie name ") // I want to display "hello" there
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, inventory)
if err != nil { panic(err) }
Run Code Online (Sandbox Code Playgroud)
如您所见,我的地图键中有空格name of the movie.如何在parse参数中显示hello(哪个是值name of the movie)?
使用索引功能: Movie name: {{index . "name of the movie"}}
来自文档:
index
Returns the result of indexing its first argument by the
following arguments. Thus "index x 1 2 3" is, in Go syntax,
x[1][2][3]. Each indexed item must be a map, slice, or array.
Run Code Online (Sandbox Code Playgroud)