If statement not functioning

Having trouble with Hugo getting this logic to work.

Am trying to set a thumbnail for the list view based on some logic:

  • If there is a thumbnail show that (works)
  • If no thumbnail but an image, then show image (works)
  • if there isn’t an image, then show an image that corresponds with the category. (the issue below)

The category can occasionally have two values, so the frontmatter looks like this:

categories:
- number1
- number2

Or it could occasionally have just one value

categories:
- one

Have tried using some logic to test to see if it is a string or if it is an array if the front matter looks like the below, but the logic just gets bypassed.

categories: one

Inside the logic it sets the .Params.categories to a value, however I receive a build error if the value isn’t defined outside of the logic.

For example

    {{ if .Params.categories}}
      {{ $category := index (.Params.categories) 0}}
    {{else}}
      {{ $category:= ""}}
    {{end}}

Am I wrong thinking that if there is no category it should default $category to nothing?

Have also tried

    {{ $category:= ""}}
    {{ $cat := string .Params.categories}}
    {{ if eq (printf "%T" $cat) "string" }}
      {{ $category := $cat}}
    {{ else }}
      {{ $category := index ($cat) 0 }}
    {{end}}

However result always is “” and it never hits the logic.

Also went down the route of

    {{ $cat := .Params.categories}}
    {{ $type := (printf "%T" $cat) }}
    {{ $typeIsString := (findRE "^(string|template\\.(CSS|HTML|HTMLAttr|JS|JSStr|URL))$" $type) }}
    {{ $typeIsSlice := (findRE "^([[][]]|.*TaxonomyList|output\\.Formats|resource\\.Resources|.*navigation\\.Menu$|\\*?hugolib\\.Pages$|hugolib\\.OrderedTaxonomy$|hugolib\\.WeightedPages)" $type) }}
    {{if $typeIsSlice}}
      {{ $category := index ($cat) 0 }}
    {{ else if $typeIsString}}
      {{ $category := $cat}}
    {{ else }}
      {{ $category := "bob"}}
    {{end}}

However $category will never show bob and the page build error with

undefined variable "$category"

This logic is all within an else if statement if that makes any difference.
Appreciate any help!

Use := to initialize a variable.
Use = to change its value.

{{ $a := "" }}
{{ if true }}
  {{ $a = "foo" }}
{{ else }}
  {{ $a = "bar" }}
{{ end }}

{{ $a }} --> foo

https://pkg.go.dev/text/template#hdr-Variables

3 Likes

Lifesaver, thank you!

Knew I was missing something.

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