Home > Backend Development > Golang > How to Access the Name Field of the First Array Element in Go Templates?

How to Access the Name Field of the First Array Element in Go Templates?

Mary-Kate Olsen
Release: 2024-11-07 13:35:03
Original
1005 people have browsed it

How to Access the Name Field of the First Array Element in Go Templates?

Accessing the .Name Field of the First Array Element in Go Templates

In HTML templates, you may face situations where you need to access the value of the first index of an array. However, simply using the "index" function may not suffice, especially when trying to obtain specific fields within the array.

To address this challenge, the correct syntax involves grouping the expression and applying the ".Name" selector to retrieve the desired value. Consider the following template:

<div>Foobar {{ (index .Doc.Users 0).Name }}</div>
Copy after login

In this template, the ".Doc.Users" array contains objects with a "Name" field. By grouping the "index .Doc.Users 0" expression and applying ".Name," you effectively select the "Name" field of the first array element.

For a practical example, imagine you have an object with an array of users:

import "fmt"
import "os"
import "text/template"

type User struct {
    Name  string
    Email string
}

func main() {
    t := template.Must(template.New("").Parse(
        `<div>Foobar {{ (index .Doc.Users 0).Name }}</div>`))

    m := map[string]interface{}{
        "Doc": map[string]interface{}{
            "Users": []User{
                {Name: "Bob", Email: "[email protected]"},
                {Name: "Alice", Email: "[email protected]"},
            },
        },
    }

    fmt.Println(t.Execute(os.Stdout, m))
}
Copy after login

When you run this code on the Go Playground, you will obtain the following output:

<div>Foobar Bob</div>
Copy after login

This demonstrates the effective retrieval of the ".Name" field from the first element of the ".Doc.Users" array within your Go template.

The above is the detailed content of How to Access the Name Field of the First Array Element in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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