I was struggling with conditional variables in templates for a while, especially when checking for properties that may not exist. Other than writing giants blocks of if else conditions I also kept running into can't evaluate field context in type
errors. Not being super familiar with Go I wasn’t getting very far, and searching was not helpful.
I finally figured it out, and hopefully this post helps others. In my case I was trying to write a partial that could output links from multiple sources. I wanted to default to Permalink
but fall back to URL
in the case of menu items defined in config. For these menu items Permalink
wasn’t defined and kept throwing the can't evaluate...
error.
What failed:
{{ $url := "EMPTY" }}
{{ if .Permalink }}
{{ $url = .Permalink }}
{{ else }}
{{ $url = .URL }}
{{ end }}
<a href={{ $url | safeURL }}>My link</a>
What ended up working was double negation:
{{ $url := "EMPTY" }}
{{ $hasPermalink := not (not .Permalink) }}
{{ $url = cond $hasPermalink .Permalink .URL }}
<a href={{ $url | safeURL }}>My link</a>
Whoop! Happy Coding!
- Admins, if this is a duplicate, or has been mentioned somewhere else I was unable to find it. Feel free to delete.