Home >Backend Development >Golang >How to Access Struct Field of Map Element in HTML Template with Go?

How to Access Struct Field of Map Element in HTML Template with Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 07:27:02976browse

How to Access Struct Field of Map Element in HTML Template with Go?

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!

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