Understanding where

In a partial, I have

{{- range .Site.Menus.main -}}
{{- if eq .Post "left" -}}
...

This processes all main menu items that have post = "left".
I was under the assumption that I could replace this by:

{{- range where .Site.Menus.main "Post" "left" -}}
...

but this returns no pages.

Am I overlooking something trivial?

Maybe

{{- range where .Site.Menus.main ".Post" "left" -}}

I am pretty sure I would try with post and .Post before landing on Post.

The way I remember is, that the variables of the menu only exist inside of menu templates (“loops”). That means that may be inside of a range you have no menu object “resolved” and thus no .Post variable available that you could test to, resulting in the range returning false for each item. This might be why you found the first two liner template. Inside of the range you have the menu variables available, but not when the range is executed… But that is just an idea, not based on knowledge :wink:

I did a quick check on all my templates and always have only a range .Site.Menus.name for all menus.

Did all that, and more…

Doesn’t sound unrealistic. Let’s hear them Gods.

{{- range where .Site.Menus.main "Post" (safeHTML "left") -}}

What is the difference between what is returned by "left" and (safeHTML "left")? I don’t see anything that might be different in what that change gives back? There is no HTML in that string and nothing that would be escaped. Is there anything that is returned additionally like a marker that the string has a certain meaning that is used by the range function?

{{ $var := safeHTML "left" }}
{{ printf "%T" $var }}

template.HTML

{{ $var := "left" }}
{{ printf "%T" $var }}

string

See https://github.com/gohugoio/hugo/blob/master/navigation/menu.go#L37-L38

This statement attempts to compare two different types:

{{- range where .Site.Menus.main "Post" "left" -}}

The following statement works because .Post has already been cast to a string:

{{- if eq .Post "left" -}}

See https://github.com/gohugoio/hugo/blob/master/navigation/menu.go#L122-L125.

3 Likes

Perfect explanation. Thanks!

Surprising, unexpected, non-intuitive but understandable :grin: .

Docs:

This value typically contains a string representing HTML.

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