Home >Backend Development >Golang >How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?
You want to access the fields of a struct stored in a map using the html/template package in Go.
The default Go templates do not allow access to unexported fields of a struct. To enable this, you need to export the fields by capitalizing the first letter of their names.
Define the Struct with Exported Fields:
<code class="go">type Task struct { cmd string args []string Desc string // Note the capital "D" }</code>
Initialize the Map with Exported Structures:
<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", }, }</code>
Parse and Execute the Template:
<code class="go">func listHandle(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("index.tmpl") t.Execute(w, taskMap) }</code>
Template File:
<code class="go"><html> {{range $key, $value := .}} <li>Task Name: {{$key}}</li> <li>Task Value: {{$value}}</li> <li>Task description: {{$value.Desc}}</li> {{end}} </html></code>
The template will now be able to access the exported fields of the Task struct in the map:
<code class="html"><html> <li>Task Name: find</li> <li>Task Value: {find [/tmp/] find files in /tmp dir}</li> <li>Task description: find files in /tmp dir</li> <li>Task Name: grep</li> <li>Task Value: {grep [foo /tmp/* -R] grep files match having foo}</li> <li>Task description: grep files match having foo</li> </html></code>
The above is the detailed content of How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?. For more information, please follow other related articles on the PHP Chinese website!