【问题标题】:Get an element of a struct array by attribute value in a Golang template通过Golang模板中的属性值获取结构数组的元素
【发布时间】:2022-01-26 17:29:37
【问题描述】:

我想在 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) }}"/>

非常感谢任何提示

【问题讨论】:

    标签: go woocommerce go-templates


    【解决方案1】:

    使用模板没有简单的方法可以做到这一点。你要先找到你需要的条目,然后看它的内容

    {{$name := "" }}
    {{ range .Product.Attributes }}
    {{if eq .Name "Hersteller"}}
       {{$name = (index .Options 0)}}
    {{end}}
    {{ end }}
    <input type="text" value="{{$name}}"/>
    

    【讨论】:

    • 简单到可以解决我的问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    相关资源
    最近更新 更多