Best practice for default only on nil not falsy

I would like to know if there is a better way of doing the following:

{{- $omitFromSitemap := false -}}
{{- if (isset .Page.Params "omitFromSitemap") -}}
	{{- $omitFromSitemap = .Page.Params.omitFromSitemap -}}
{{- else if (isset site.Params "omitFromSitemap") -}}
	{{- $omitFromSitemap = site.Params.omitFromSitemap -}}
{{- end -}}

Note that default will not do what I want because I do not want a value of false in .Page.Params.omitFromSitemap overridden. From what I recall, default overrides based on ‘falsyness’ not only on nil.

If I’m wrong I’ll have to figure out why I got that impression, since it seemed to the behavior with templates I’ve written.

The .Param method on .Page saves you some code.

{{ $omitFromSitemap := or (.Param "omitFromSitemap") false }}

We have to use or with a final false argument to defend against the absence of either page or site parameters. Otherwise we’d get nil instead of false.

Though in most cases nil would be sufficient.

1 Like

Thank you. I forgot about .Param. I got out of the habit of using it when I was doing partials that I designed for one to also call from shortcodes. In older versions of Hugo site (and things like .Param that used it implicity) didn’t work in shortcodes.

BTW, if you wanted the default to be true you’d need to use and.

{{ $omitFromSitemap := and (.Param "omitFromSitemap") true }}
1 Like

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