Union/Intersect of slice variable and metadata

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.

You’ve found a shortcoming in the union implementation. intersect has a similar problem, which I’ve proposed to fix in PR#3328. Essentially, union doesn’t know how to compare a []interface{} with a []string. I’ve created an issue in GH to track this:

https://github.com/spf13/hugo/issues/3411

1 Like

Ah, I just spent hours on this issue, and was totally confused why union didn’t work. Thanks for the fix, and hope it will be accepted.