gpt4 book ai didi

go - 通过Golang模板中的属性值获取结构数组的元素

转载 作者:行者123 更新时间:2023-12-05 04:38:56 32 4
gpt4 key购买 nike

我想在 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”的元素的“选项”数组 (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}}"/>

关于go - 通过Golang模板中的属性值获取结构数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70500739/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com