Home  >  Article  >  Backend Development  >  How to Access Struct Fields of Map Elements in HTML Templates Using Go\'s html/template Package?

How to Access Struct Fields of Map Elements in HTML Templates Using Go\'s html/template Package?

DDD
DDDOriginal
2024-10-24 07:34:30255browse

How to Access Struct Fields of Map Elements in HTML Templates Using Go's html/template Package?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn