"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access Nested Struct Fields in HTML Templates in Go?

How to Access Nested Struct Fields in HTML Templates in Go?

Published on 2024-11-17
Browse:740

How to Access Nested Struct Fields in HTML Templates in Go?

How to Access Struct Fields of Map Elements in HTML Templates in Go

This article addresses the issue of retrieving struct fields from map elements within HTML templates using the html/template package in Go.

Consider the following Task struct:

type Task struct {
   Cmd string
   Args []string
   Desc string
}

Furthermore, a map is initialized with Task structs as values and strings as keys:

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",
    },
}

Now, let's examine the issue at hand. A template is being used to parse an HTML page:

func listHandle(w http.ResponseWriter, r *http.Request){
    t, _ := template.ParseFiles("index.tmpl")
    t.Execute(w, taskMap)
}

The following code snippet represents the index.tmpl template:


{{range $key, $value := .}}
   
  • Task Name: {{$key}}
  • Task Value: {{$value}}
  • Task description: {{$value.Desc}}
  • {{end}}

    This approach successfully outputs the map's keys and values, but attempts to access the Task fields within the template, for example using {{$value.Desc}}, result in errors.

    The solution lies in exporting the fields you wish to access within the templates. This can be achieved by capitalizing the first letter of the field names:

    type Task struct {
       Cmd string
       Args []string
       Desc string
    }

    Consequently, references to field names within the template must also be capitalized:

    
    {{range $key, $value := .}}
       
  • Task Name: {{$key}}
  • Task Value: {{$value}}
  • Task description: {{$value.Desc}}
  • {{end}}

    By following these steps, you can successfully retrieve and display the Desc field of each Task in the template.

    Release Statement This article is reprinted at: 1729726421 If there is any infringement, please contact [email protected] to delete it
    Latest tutorial More>

    Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

    Copyright© 2022 湘ICP备2022001581号-3