Retrieving Struct Field of Map Element in HTML/Template's Go Package
Situation:
You have a struct and a map using the struct as a value. You desire to access the struct's fields within an HTML page rendered using the html/template package.
Solution:
To enable access to the struct's fields within the template, they must be exported. Exporting a field entails beginning its name with an uppercase letter.
Detailed Explanation:
<code class="go">type Task struct { cmd string args []string Desc string // Exported field }</code>
Notice the uppercase 'D' in Desc.
Similarly, update the map and template references:
<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>
<code class="html">{{range $key, $value := .}} <li>Task Name: {{$key}}</li> <li>Task Value: {{$value}}</li> <li>Task description: {{$value.Desc}}</li> {{end}}</code>
Results:
The output will contain the Desc field for each task:
<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>
Note: This solution exports the entire struct, so consider using a defined template function if you only need specific fields.
The above is the detailed content of How to Access Struct Fields of Map Elements in HTML Templates Using Go\'s html/template Package?. For more information, please follow other related articles on the PHP Chinese website!