Querify a dict structure

I have a dict structure that I would like to transform into a URL-query string:

structure

{{- $avatar := dict -}}
{{- $avatar = merge $avatar (dict "size" ($avatarConfig.size | default 128)) -}}
{{- $avatar = merge $avatar (dict "font-size" ($avatarConfig.fontSize | default 0.5)) -}}

result

?size=128&font-size=0.5

I know querify but that seems to work only on “flat” items. Is there anything similar available for a dictionary or do I have to range through the dict myself?

If #8305 is merged, you’ll be able to pass a slice, but not a map, to querify. That will help you a little, but you’ll still have to range through the map.

{{ $qs := slice }}
{{ range $k, $v := $avatar }}
  {{ $qs = $qs | append $k $v }}
{{ end }}
{{ querify $qs }}

If you do this kind of thing frequently…

layouts/partials/map-to-slice.html

{{ $slice := slice }}

{{ if reflect.IsMap . }}
  {{ range $k, $v := . }}
    {{ $slice = $slice | append $k $v }}
  {{ end }}
{{ else }}
  {{ errorf "The argument passed to the map-to-slice partial must be a map." }}
{{ end }}

{{ return $slice }}

Then:

{{ querify (partial "map-to-slice.html" $avatar) }}

But remember, this is predicated on #8305 being merged.

2 Likes