New "has" operator to where?


#1

Hello there,

I have a project with novel/characters manyToMany relationship.

I assigned ids to each novel, and then added a .Params.novel to each character with a map of novels as such:

---
title: Who Ever
type: character
novel:
  - a-novel-about-this
  - a-novel-about-that
---

Now, on a character page I can call the novels he/she appears in using:

{{ range where .Site.Pages.ByTitle ".Params.id" "in" .Params.novel }}

On my novel page though, in order to list their characters I have to use a range + .Scratch hack:

{{ range where .Site.Pages.ByTitle "Type" "character" }}
    {{ if in .Params.novel $.Params.id }}
        {{ $.Scratch.Add "characters" (slice . )}}
    {{ end }}
{{ end }}
{{ range .Scratch.Get "characters" }}

I wondered if there was a more convenient way using where and if not, if it would be too complicated to add has as a new where operator so something like this could be used instead:

{{ range where .Site.Pages.ByTitle ".Params.novel" "has" .Params.id }}

#2

Have you tried

{{ range where .Site.Pages.ByTitle “.Params.novel” “intersect” .Params.id }}

Or maybe you have to do:

{{ range where .Site.Pages.ByTitle “.Params.novel” “intersect” (slice .Params.id) }}


#3

I’d also suggest seeing if https://gohugo.io/content-management/related/ can help you here. I’ve used it and it’s much more efficient than other approaches.


#4

Didn’t think about wrapping my lone value in a slice when I tried intersect!
Works like a charm.

I guess my suggestion for a “has” operator doesn’t make a lot of sense now… Hard to find another use case for it.

Thanks a lot!


#5

Interesting I have been searching/trying for the best way to manage relationships with Hugo. I will look into “related”.


#6

I can help if you need it. I’ve done it a fair amount.


#7

Thanks to bep example, it makes me think I need to update my nested where statements to use intersect (which I have not used yet)

for example:

{{ $filtervariable := where (where (where (where .Site.Pages "Type" "contenttype) ".Params.param1" "=" "off") ".Params.param2" "=" "negative") ".Params.param3" "=" "high" }}

{{ range $filtervariable.ByLinkTitle }}
    {{ .Render "summary" }}
{{ end }}