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

Susan Sarandon
Release: 2024-10-24 07:55:30
Original
545 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!