Coding Challenge: Create array from value in array of maps in frontmatter

Given the following frontmatter

--- 
date: 2016-03-14 21:21:41 +0000
author: Jim
versions:
-
  id: "a6"
  some_other_key: 2
-
  id: "a7"
  some_other_key: 3
-
  id: "a8"
  some_other_key: 23
---

How would I get an array of version ids? It needs to be an array variable (ex $ids) that can be passed to a partial or also output with the delimit function as so.

{{ delimit $ids ", " }}

// Outputs a6, a7, a8

I’ve tried everything I can come up with from the documentation, but can’t get anything to work.

1 Like
{{- range $i, $kw := .Params.versions -}}
  {{- if $i -}}, {{- end -}}
  {{ .id }}{{ .some_other_key }}
{{- end }}

It will only work if the .Params.versions is not taxonomy.

2 Likes

This is a bit of a hack, but one way would be to use the Scratch feature. Untested example:

{{ range $i, $v := .Params.versions }}
{{ with $v.id }}{{ $.Scratch.SetInMap "ids" . . }}{{ end }}
{{ end }}

{{ delimit ($.Scratch.GetSortedMapValues "ids") ", " }}
3 Likes

Thanks for the reply. I’m still getting my head around these Go Templates. Your solution works for printing what I need on the screen. Could you explain how this line works because it gives the desired result but I don’t understand why.

{{- if $i -}}, {{- end -}}

Scratch! Wow, I somehow overlooked that in the docs. That does exactly what I need and seems to work perfectly!

The numbering starts from zero, so during the first passing $i = 0. As a result, “if” condition is not executed and a comma is not added.

1 Like