Menu .Pre Property

While iterating through a menu defined in the config file, I want use the current value or existence of .Pre for the current menu item, but I can’t seem to find anything that works. Basic idea in pseudocode:

range .Site.Menus.menu
    if .Pre has a value or exists
        ...
    else
end

Using printf I see what I want (some blank output, some with html string). I’ve tried the following:

if (isset . .Pre) - always returns false; is that the right context to use?
if (eq .Pre "") - always returns false, even when printf shows no output

It’s worth noting that .Pre is of type template.HTML, but docs also say the value contains a string representing HTML.

Try:

{{ with .Pre }}
  {{ . }} 
{{ end }}

It will only print the value if it exists

Tried that as well (should have mentioned it), but lost access to the rest of the menu variables like .Title wasn’t sure how to use $ to get back to it.

Or is there a better way to control how with resets context?

Yep there are multiple ways to handle this. Show us your full menu code and we’ll be able to help you better

You could try something like

{{if gt (len .Pre) 0 }}
  whatever
{{else}}
  something else
{{end}}

This is the menu loop where I was trying to logically test .Pre, simplified down to question at hand:

{{- range .Site.Menus.header -}}
    {{ with .Pre }}{{ .Pre }}<span>{{ .Title }}</span>{{ else }}{{ .Title }}{{ end}}
{{ end }}

With this, .Title was not in context Inside the {{ with }}. I worked around by adding the tags to the pre and post variables in config.toml, but I’d prefer to keep the structural change in the template.

Could also be solved with adding a class to the span based on {{ with .Pre }}, but I also wanted to understand why .Pre seemed to not respect isset and eq string compare.

Try this – the value of the $pre variable will default to .Title, and will only be assigned the .Pre value if it exists.

{{ range .Site.Menus.header }}
  {{ $pre := .Title }}
  {{ with .Pre }}{{ $pre = . }}{{ end }}
  <span>{{ $pre }}</span>
{{ end }}

Thanks, def another good way to work around this, I’ve got it working now.

I’d still like to understand why .Pre didn’t respect isset or eq “” tests, but at least not a roadblock.

Well, if .Pre doesn’t exist, then it would be nil. And nil does not equal empty string. So that fact that it returned false is not surprising.

Yea, which is why I started with isset, which seems like the right function for checking a variable exists.