Home > Article > Backend Development > 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>
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>
To understand this syntax, let's break it down:
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)) }
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>
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!