Home >Backend Development >Golang >How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?

How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 07:55:30635browse

How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?

How to Access Struct Fields in HTML Templates in Go

Problem

You want to access the fields of a struct stored in a map using the html/template package in Go.

Solution

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.

Code Example

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>

Output

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!

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