所以我在使用它時有 html 模板,我得到了對象:<div>Foobar {{ index .Doc.Users 0}}</div>輸出:<div>Foobar {MyName [email protected]}</div>我只想使用Name我嘗試過多次迭代但沒有成功的領域:{{ index .Doc.Users.Name 0}}{{ index .Doc.Users 0 .Name}}{{ .Name index .Quote.Clients 0}}...僅獲取數組中第一個元素的.Name字段 ( )的正確語法是什么?.Doc.Users[0].Name
1 回答

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
只需對表達式進行分組并應用.Name選擇器:
<div>Foobar {{ (index .Doc.Users 0).Name }}</div>
這是一個可運行、可驗證的示例:
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: "[email protected]"},
{Name: "Alice", Email: "[email protected]"},
},
},
}
fmt.Println(t.Execute(os.Stdout, m))
輸出(在Go Playground上嘗試):
<div>Foobar Bob</div><nil>
(<nil>末尾是 返回的錯誤值template.Execute(),表明執行模板沒有錯誤。)
- 1 回答
- 0 關注
- 369 瀏覽
添加回答
舉報
0/150
提交
取消