Use `apply` as a "map()" equivalent

I wonder if there is an easy way to use apply to build an array of say the “.Title” of given pages or other parameter from an array of pages other than by creating a dedicated returning partial.

It seems that apply could take any kind of “dynamic” parameter, but so far, I was only able to pass the dot as “.” as argument. For example:

{{ $tags := apply site.RegularPages "index" ".Params" "tags" }}

The above will not work, as index will try and evaluate the sring “.Params” instead of the .Params of the given entry.

But the following:

{{ $entries := slice
	(dict
		"name" "Peter"
	)
	(dict
		"name" "John"
	)
	(dict
		"name" "Harry"
	)
}}
{{ with apply $entries "index" "." "name" }}
	{{ range . }}
		{{ warnf "%#v" . }}
	{{ end }}
{{ end }}

Will work, as “.” is taken for what it is, a map.

Is there something I am missing? This might not seem critical, but we’re often in a position where we have to do more gymnastic to isolate the key of an entry like so which I would suspect might be resource costful for hundreds of entries:

{{ $entry_names := slice }}
{{ range .Pages }}
	{{ $entry_names = $entry_names | append .Title }}
{{ end }}

The underlying limitation seems to be:

{{ index .Page "Title" }} --> error calling index: can’t index item of type hugolib.pageState

So here’s an ugly workaround that throws a .Path warning:

{{ apply (site.RegularPages | jsonify | unmarshal) "index" "." "Title" }}

Or to get an array of arrays for the tags:

{{ apply (site.RegularPages | jsonify | unmarshal) "index" "." "Params" "tags" }}
1 Like

Yes that’s pretty smart… I’ll try that! Thanks!