Accessing the Value of the First Index of an Array in Go Templates
When using HTML templates with Go, you may encounter situations where you need to access the value of the first index of an array. To address this challenge, let's explore the correct syntax for extracting the desired data.
The provided code snippet illustrates an attempt to access the Name field of the first element in an array within the template:
<div>Foobar {{ index .Doc.Users 0}}'</div>
However, this approach doesn't achieve the desired result since {{ index .Doc.Users 0}} returns the entire first element of the array, including both the Name and Email fields. To obtain just the Name field, you need to group the expression and apply the .Name selector as follows:
<div>Foobar {{ (index .Doc.Users 0).Name }}</div>
In this improved syntax, the index function returns the first element of the Doc.Users array, which is then coerced into parentheses to group the expression and subsequently provide access to the Name field.
For example:
type User struct { Name string Email string } 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: "user1@example.com"}, {Name: "Alice", Email: "user2@example.com"}, }, }, } fmt.Println(t.Execute(os.Stdout, m))
Output:
<div>Foobar Bob</div><nil>
This updated code produces the desired output, where the Name field of the first element in the Doc.Users array is successfully retrieved within the template.
The above is the detailed content of How to Access the Name Field of the First Element in an Array in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!