Find all occurrences of a key in a yaml file

Hi, I’m trying to render some content from a YAML data file.
I need to process every occurrence of the “repository” key, but it’s not always at the same level.
The YAML looks something like this:

spec:
  name1:
    key1:
      enabled: true
      image:
        repository: example.com/1
    key2:
      repository: example.com/2
  name2:
      repository: example.com/3
  name3:
      key3:
         key4:
            repository: example.com/4

Is there an easy way to range through all “repository” values, without having to know the exact path to them? (I hope it can be done with a well-aimed “range where” expression, but couldn’t get it right.)

Thanks,
Robert

No. You need a recursive template.

layouts/partials/get-repositories.html

{{- template "dig" . -}}

{{- define "dig" -}}
  {{- range $k, $v := . -}}
    {{- if reflect.IsMap . -}}
      {{- template "dig" . -}}
    {{- else -}}
      {{- if eq $k "repository" -}}
        {{- printf "%s\n" $v -}}
      {{- end -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
{{- /* Chomp trailing newlines. */ -}}

This calls the partial, puts the results into a slice, then ranges through the slice:

{{ $reposString := partial "get-repositories" site.Data.foo | chomp }}
{{ $reposSlice := split $reposString "\n" }}
{{ range $reposSlice }}
  {{ . }}<br>
{{ end }}
1 Like

Thanks a lot for the help, it works great!

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