英文:
Golang Template property of struct in Index
问题
我有一个使用golang模板的json字符串。有没有办法打印出{{index .Apps 1}}的Name属性?以下是我正在运行的代码。在第31行,我试图只打印Apps[0]的Name属性。
package main
import (
	"encoding/json"
	"os"
	"text/template"
)
type Message struct {
	Name    string
	Id      int
	Apps    []App
	Company Company
}
type App struct {
	Name   string `json:"name"`
	Device string `json:"device"`
}
type Company struct {
	UserId string
}
func main() {
	msg := []byte(`{
		"Name":"Bob",
		"Id":1,
		"apps":[{"name":"app1","device":"ios"},{"name":"app2","device":"android"},{"name":"app3","device":"ios"}],
		"company":
		{
			"userId":"{{.Name}}-{{.Id}}",
			"app":["{{index .Apps 0}}","{{index .Apps 1}}"]
		}
	}`)
	var m Message
	json.Unmarshal(msg, &m)
	t := template.New("My template")
	t, _ = t.Parse(string(msg))
	t.Execute(os.Stdout, m)
}
英文:
I have a json string that uses golang Template. Is there a way to print the Name property of {{index .Apps 1}}? Below is the code I am running. On line 31, I am trying to just print the Name property of Apps[0].
http://play.golang.org/p/4RNevdqxP1
package main
import (
  "encoding/json"
  "os"
  "text/template"
)
type Message struct {
   Name    string
   Id      int
   Apps    []App
   Company Company
}
type App struct {
   Name   string `json:"name"`
   Device string `json:"device"`
}
type Company struct {
  UserId string
 }
func main() {
  msg := []byte(`{
  "Name":"Bob",
  "Id":1,
  "apps":[{"name":"app1","device":"ios"},{"name":"app2","device":"android"},    {"name":"app3","device":"ios"}],
  "company":
  {
	"userId":"{{.Name}}-{{.Id}}",
	"app":["{{index .Apps 0}}","{{index .Apps 1}}"]
  }
}`)
var m Message
json.Unmarshal(msg, &m)
t := template.New("My template")
t, _ = t.Parse(string(msg))
t.Execute(os.Stdout, m)
}
答案1
得分: 7
你可以用括号将其包裹起来:
{{(index .Apps 1).Name}}
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论