text / template:地图中的空格键

时间:2015-01-27 00:19:15

标签: templates go

我有以下代码(使用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参数中显示helloname of the movie的值)?

1 个答案:

答案 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.