How to fix messy template logic?

I have the following in my partials/header.html:

  <meta name="description" content="{{if .IsHome}}{{.Site.Params.description}}{{end}}{{if .Description}}{{.Description}}{{end}}
  {{if .Params.about}}{{.Params.about}}{{else}}{{.Params.name}} {{delimit .Params.location " "}}
  {{delimit .Params.apple " "}} {{delimit .Params.banana " "}}
  {{delimit .Params.pear " "}} {{delimit .Params.kiwi " "}}
  {{.Params.pineapple}}{{end}}">

Unfortunately it doesn’t work as I would like and the template looks really messy with this logic.

What I’m trying to accomplish is to set the meta description depending upon the following:

  1. IF homepage ->
    <meta name="description" content="{{.Site.Params.description}}">

  2. IF NOT homepage AND .Params.description -> .Params.description
    <meta name="description" content="{{.Params.description}}">

  3. IF NOT homepage AND NOT .Params.description AND .Params.about -> .Params.about
    <meta name="description" content="{{.Params.about}}">

  4. IF NOT homepage AND NOT .Params.description AND NOT .Params.about ->
    <meta name=“description” content="{{.Params.name}} {{delimit .Params.location " "}}
    {{delimit .Params.apple " "}} {{delimit .Params.banana " "}}
    {{delimit .Params.pear " "}} {{delimit .Params.kiwi " “}}
    {{.Params.pineapple}}”>

Changing the way that the Params are declared in the frontmatter isn’t an option.

There’s no way to avoid a messy template with the logic you need. When Go 1.6 comes out, this can get a little cleaner, but for now, you’ll need to something like this:

{{ if .IsHome }}{{ .Site.Params.description }}
{{ else if ne .Description "" }}{{ .Description }}
{{ else if isset .Params "about" }}{{ .Params.about }}
{{ else }}
{{ .Params.name}} {{ delimit .Params.location " " }}
{{ delimit .Params.apple " "}} {{ delimit .Params.banana " " }}
{{ delimit .Params.pear " "}} {{ delimit .Params.kiwi " " }}
{{ .Params.pineapple }}
{{ end }}

And the ugliest part of all is that I’d put all of that on a single line so that my HTML tag would be on a single line. Go 1.6 templates will let you control whitespace similar to how jinja2 works:

<meta content="{{ if ... }}
  {{- else if ... }}{{ .Description }}
  {{- else if ... }}{{ ... }}
  {{- end }}">

I’m anticipating that Hugo 0.16 will be built with Go 1.6. Cross your fingers!

1 Like

Thank you!

I’ll definitely revisit this when Go 1.6 is released and Hugo gets the new template features.