Hugo template syntax: With + default

Hi! I’m just getting started creating and launching my first Hugo site, and I’m having a blast.

I came across a little problem earlier, and thought I could use it to expand my knowledge. Perhaps it would be fun for some of you to have a go at solving it, too.

The problem

My site’s theme has Calls To Action, which are stored essentially at site.Data.homepage.cta.

By default it displays the attractive and eyecatching partial cta.html twice—once near the top and once at the bottom of the homepage.

I wanted to make a cute little setup where the bottom cta.html will use a cta2 element from the front matter, but will default however to plain old cta if none exists. The idea is to use cta2 for time-limited special offers and the like.

{{ if site.Data.homepage.cta.enable }}
  {{ with (default site.Data.homepage.cta (site.Data.homepage.cta2)) }}
    {{ partial "cta.html" . }}
  {{ end }}
{{ end }}

I’ve tried doing something like the above, but plainly I’ve got the wrong idea about the template syntax, and it just makes Hugo angry and errorful. So how can I go about it?

ADDENDUM: Remember, people will come here from Google looking for an answer, so please try and answer my question in the general case, rather than picking apart the particular mistakes I’ve made in the code above or just saying “You can’t / shouldn’t / don’t want to do that”. Thanks!

Try something like this:

{{ with site.Data.homepage.cta2 | default site.Data.homepage.cta }}

I haven’t tried that format with with. I usually do it this way:

{{ with or (site.Data.homepage.cta2) (site.Data.homepage.cta) }}

:slight_smile:

1 Like

techmagus
Try something like this:

{{ with site.Data.homepage.cta2 | default site.Data.homepage.cta }}

Thanks! That works perfectly. Actually, it’s what I thought I tried. But I didn’t know that you could use or in ‘assignment’ like you might in a regular scripting language, so I’m glad I asked. Thanks a lot! :upside_down_face:

EDIT: Actually, turns out I have a worse problem where the code works until I restart Hugo… think it’s worth starting a new thread about this one.

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