Unexpected behaviour fetching a list of tags vs a single tag

I have made a shortcode that selects all pages with a specific tag (in a given section) and it looks like this:

{{ $taggedPages := where (where .Site.Pages "Section" "portfolio") "Params.tags" "a-tag" }}
# The tag is actually fetched from the shortcode variable (.Get "tags")…

This code works fine when a page has only one tag in the frontmatter, but not when tags are listed:

# This works
tags: a-tag

# This does not work
  - a-tag

I suspect I need to treat a list/array of tags slightly differently when making the selection, but I don’t know how. Can anyone point me in the right direction?

There is an in command that you can call like “where in array-of-somethings something”.

That second parameter is an array, even with a single item. So you have to decide what format you want to use or you have to check if your frontmatter variable is a string or an array (which in Golang is called slice (a slice of strings))

Thanks for the reply, @davidsneighbour.

I have decided to only define tags in frontmatter as an array – the problem is that a simple .Params.tags does not return the tags in the array as I expect. It only works if add one tag as a string, which I do not want.

The code has changed a bit, as it is moved to a layout file, and looks like this:

{{ $selection := .Pages }}
{{ if isset .Params "tags" }}
    {{ $tags := .Params.tags }}
    {{ $selection = where .Site.Pages "Params.tags" $tags }}
{{ end }}
{{ range where site.Pages "Params.tags" "intersect" (slice "foo" "bar") }}


1 Like

Thank you, it worked! I have not used intersect and slice that much yet, so the solution was not immediately obvious. Learning as I go :slight_smile:

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