Accessing Struct Field of Map Element in HTML Template with Go
When working with maps and structs in Go templates, it's important to ensure that fields can be accessed from the template. In this case, the taskMap holds Task structs as values, and the task descriptions are accessed using ".desc".
To access the fields in the template, they must be exported. This is achieved by capitalizing the field name in the struct definition:
<code class="go">type Task struct { cmd string args []string Desc string // Capitalized to export the field }</code>
Similarly, update the map entries and template references by capitalizing "Desc":
<code class="go">var taskMap = map[string]Task{ "find": Task{ cmd: "find", args: []string{"/tmp/"}, Desc: "find files in /tmp dir", }, "grep": Task{ cmd: "grep", args:[]string{"foo","/tmp/*", "-R"}, Desc: "grep files match having foo", }, } <html> {{range $key, $value := .}} <li>Task Name: {{$key}}</li> <li>Task Value: {{$value}}</li> <li>Task description: {{$value.Desc}}</li> {{end}} </html></code>
With these modifications, the template will successfully display the description field for each task.
The above is the detailed content of How to Access Struct Field of Map Element in HTML Template with Go?. For more information, please follow other related articles on the PHP Chinese website!