我有以下代码(使用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) }
如您所见,我的地图键name of the movie
中有空格。如何在parse参数中显示hello
(name of the movie
的值)?
答案 0 :(得分:5)
使用索引功能:Movie name: {{index . "name of the movie"}}
来自the docs:
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.