在Golang中,可以使用模板来访问结构体的属性。

huangapple go评论77阅读模式
英文:

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}}

Playground链接

英文:

You can wrap it in parenthesis:

{{(index .Apps 1).Name}}

<kbd>Playground link</kbd>

huangapple
  • 本文由 发表于 2014年7月30日 10:29:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/25027857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定