Home > database >  Get an element of a struct array by attribute value in a Golang template
Get an element of a struct array by attribute value in a Golang template

Time:12-28

I want to display the value of a certain WooCommerce product custom attribute in a Golang template.

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"`
   }
   ...
}

An actual json object looks like this:

{
   ...
   "attributes": [
   {},
   {
      "id": 2,
      "name": "Hersteller",
      "position": 5,
      "visible": true,
      "variation": false,
      "options": [
        "Lana Grossa"
      ]
    },
   {}
   ],
   ... 
}

So from this example I want to find the first element of the 'Options' array (Lana Grossa) of the element with the name = "Hersteller" of the attributes array.

I tried to adapt the syntax to get an element by index, but could not get it to work...

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

Any hint is greatly appreciated

CodePudding user response:

There is no simple way to do this with templates. You have to first find the entry you need, and then look at its contents

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