Hi there,
A quick question about union
or intersect
functions and locally defined slices
. It’s more a question to learn more about Hugo than a support request since I found a solution (that doesn’t totally satisfies me).
Here is the use case:
My blog posts have metadata tags/taxonomies such as “dogs”, “cats”, “birds”, “horses” … :
tags: ['dogs', 'training', 'event', 'horses']
On my home page I want to display custom sections with the latest posts about (“dogs” OR “cats”). Since all my posts are already created with the tags
property, I focused on the index.html
template first.
What I tried first didn’t work. Here is what I did on the index.html file.
Note: In the final code I am using intersect
instead of union
but it was easier to use union
for this example.
{{ $selectedtags := slice "cats" "dogs"}}
{{ range .Site.Pages}}
{{union ($selectedtags) (.Params.tags)}}
{{end}}
The union returned is always empty no matter what. However, if define 2 local variables and do a union it works correctly.
However, if I define selectedtags
in my index.md metadata, then the union works correctly:
{{ $selectedtags := .Params.selectedtags}}
{{ range .Site.Pages}}
{{union ($selectedtags) (.Params.tags)}}
{{end}}
My question is: why is the union empty in the first case and not in the second one? It would be easier for me to create custom slices directly in the template to match with metadata variables.