Ad
Get An Element Of A Struct Array By Attribute Value In A Golang Template
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
Ad
Answer
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}}"/>
Ad
source: stackoverflow.com
Related Questions
- → I can't do a foreign key, constraint error
- → laravel blade templating error
- → Image does not go in database with file name only tmp name saved?
- → ListView.DataSource looping data for React Native
- → If I yield to a Promise does it wait for the Promise to be resolved before continuing
- → Browser support for class syntax in Javascript
- → Authenticate with a cookie using laravel 5.1 and jwt
- → create log file on external server-Laravel
- → Sorting Children in Laravel : How do I sort children by name?
- → What is causing the web page to reload?
- → Where is the react-devtool?
- → Function Undefined in Axios promise
- → Onclick with argument causes javascript syntax error
Ad