Range key:value pairs using select options

How I can use this option select solution to range a YAML map of Key : Value (string : int) pairs?

---
option:
  sizes: ["small","med","large"]
  color: ["red","blue","black"]
---
{{ range $variantName, $value := .Params.option }}
{{ if len $value }} <!-- check if value(array) is not empty -->

<select name="{{ $variantName }}" id="{{ $variantName }}">
  {{ range $v := $value }}
    <option value="{{ $v }}">{{ $v | humanize }}</option>
  {{ end }}
</select>

{{ end }}
{{ end }}

Perhaps scratch can be used: Iterate over scratch

Doesn’t this already work perfectly? What am I missing?

Edit: Did you wanted to pass something like this?:

---
option:
   a: 1
   b: 2
   c: 3
---

or

---
option:
   prices: ["small": 10,"med": 12,"large": 14]
---

?

Thank you! At the moment I’m using html select-options, but I’ll return to this soon. Do you have a working code ot hugo-type select-options of key-value pairs?

No, I don’t at the moment. In fact, the code you provided is the closest thing I have :joy:

What’s wrong with using that one?

Here is my current data file:

three:
  - country: Argentina
    price: 80
  - country: Armenia
    price: 60
  - country: Australia
    price: 46
  - country: Austria
    price: 28.9

Here is my current code:

{{ range $country, $price := $.Site.Data.weight.three }}
<select  class="order form-control border-0" id="select-0">
    <option value="{{ $price }}">{{ $country | humanize }}</option>
</select>
{{ end }}

It produces the following output:

0th - $map[country:Argentina price:80]
1st - $map[country:Armenia price:60]
2nd - $map[country:Australia price:46]
3rd - $map[country:Austria price:28.9]

This should be a dropdown list showing one option - but this code shows all options.
May be someone can tell me how to make it display only the country name and price, like

Argentina - 80

Thank you

1 Like

Yes, I wanted to pass something exactly like this to the dropdown:

But it does not get ranged - so I use plain html select/options. If you happen to know how to do that - please let me know.

How about this?

<select  class="order form-control border-0" id="select-0">
{{ range $.Site.Data.weight.three }}
<option value="{{ .price }}">{{ .country | humanize }}</option>
{{ end }}
</select>

The result:

 <select  class="order form-control border-0" id="select-0">
    <option value="80">Argentina</option>
    <option value="60">Armenia</option>
    <option value="46">Australia</option>
    <option value="28.9">Austria</option>
</select>

The reason is that the data structure you are ranging is a slice (of dictionaries) and not a dictionary. Each of those dictionaries has the two keys that you want, country and price.

Edit: I got distracted :upside_down_face: and answered your Dec 20’ post, not the most recent one. Send me a message of you’d like to see the other one

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.