How to Access the Value of the First Index of an Array in Go Templates?

Susan Sarandon
Release: 2024-11-07 06:15:03
Original
234 people have browsed it

How to Access the Value of the First Index of an Array in Go Templates?

Accessing the Value of the First Index of an Array in Go Templates

When working with HTML templates in Go, you may encounter the challenge of accessing the value of the first index of an array embedded within the template. Consider the following template code:

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

Here, you aim to obtain the value of the "Name" field for the first element in the "Doc.Users" slice. However, several attempts using different syntax have been unsuccessful.

The correct syntax for retrieving the "Name" field of the first element in the "Doc.Users" array is:

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

To understand this syntax, let's break it down:

  • index .Doc.Users 0: This part retrieves the first element from the "Doc.Users" slice.
  • (index .Doc.Users 0): This brackets the result of the previous expression, treating it as a single value.
  • .Name: This selector accesses the "Name" field of the value obtained from the previous expression.

By grouping the expression and applying the selector, you can effectively access the desired "Name" field.

Here's an example code that you can run to test this solution:

package main

import (
    "fmt"
    "html/template"
    "os"
)

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

This code will produce the following output, demonstrating the successful access to the "Name" field of the first user in the "Doc.Users" slice:

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

The above is the detailed content of How to Access the Value of the First Index of an Array 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