通过Golang模板中的属性值获取结构数组的元素
Get an element of a struct array by attribute value in a Golang template
我想在 Golang 模板中显示某个 WooCommerce 产品自定义属性的值。
type Produkt struct {
...
Attributes []struct {
ID int `json:"id"`
Name string `json:"name"`
Position int `json:"position"`
Visible bool `json:"visible"`
Variation bool `json:"variation"`
Options []string `json:"options"`
}
...
}
实际的 json 对象如下所示:
{
...
"attributes": [
{},
{
"id": 2,
"name": "Hersteller",
"position": 5,
"visible": true,
"variation": false,
"options": [
"Lana Grossa"
]
},
{}
],
...
}
因此,从这个示例中,我想找到属性数组中名称为“Hersteller”的元素的 'Options' 数组 (Lana Grossa) 的第一个元素。
我尝试调整语法以通过索引获取元素,但无法正常工作...
<input type="text" value="{{ (index (value .Produkt.Attributes.Name eq "Hersteller").Options 0) }}"/>
<input type="text" value="{{ (index (Name .Produkt.Attributes eq "Hersteller").Options 0) }}"/>
<input type="text" value="{{ (index (.Produkt.Attributes.Name["Hersteller"]).Options 0) }}"/>
非常感谢任何提示
没有使用模板的简单方法。你要先找到你需要的入口,然后再看它的内容
{{$name := "" }}
{{ range .Product.Attributes }}
{{if eq .Name "Hersteller"}}
{{$name = (index .Options 0)}}
{{end}}
{{ end }}
<input type="text" value="{{$name}}"/>
我想在 Golang 模板中显示某个 WooCommerce 产品自定义属性的值。
type Produkt struct {
...
Attributes []struct {
ID int `json:"id"`
Name string `json:"name"`
Position int `json:"position"`
Visible bool `json:"visible"`
Variation bool `json:"variation"`
Options []string `json:"options"`
}
...
}
实际的 json 对象如下所示:
{
...
"attributes": [
{},
{
"id": 2,
"name": "Hersteller",
"position": 5,
"visible": true,
"variation": false,
"options": [
"Lana Grossa"
]
},
{}
],
...
}
因此,从这个示例中,我想找到属性数组中名称为“Hersteller”的元素的 'Options' 数组 (Lana Grossa) 的第一个元素。
我尝试调整语法以通过索引获取元素,但无法正常工作...
<input type="text" value="{{ (index (value .Produkt.Attributes.Name eq "Hersteller").Options 0) }}"/>
<input type="text" value="{{ (index (Name .Produkt.Attributes eq "Hersteller").Options 0) }}"/>
<input type="text" value="{{ (index (.Produkt.Attributes.Name["Hersteller"]).Options 0) }}"/>
非常感谢任何提示
没有使用模板的简单方法。你要先找到你需要的入口,然后再看它的内容
{{$name := "" }}
{{ range .Product.Attributes }}
{{if eq .Name "Hersteller"}}
{{$name = (index .Options 0)}}
{{end}}
{{ end }}
<input type="text" value="{{$name}}"/>