Home > Backend Development > Golang > 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
Release: 2024-10-24 07:34:30
Original
358 people have browsed it

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

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>
Copy after login
<code class="html">{{range $key, $value := .}}
   <li>Task Name:        {{$key}}</li>
   <li>Task Value:       {{$value}}</li>
   <li>Task description: {{$value.Desc}}</li>
{{end}}</code>
Copy after login

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template