After I define my variable through conditionals, how is my variable still undefined?

I swear… I have been at Hugo for coming up on a year now and I still fail to understand things that must be pretty basic.

I’m setting a variable to be one of three values:

{{ if or ( eq .Params.category "Stairs") (in .Params.category "Stairs")}}
  {{ $category := "Stairs" }}
{{ else if or ( eq .Params.category "Steel") (in .Params.category "Steel")}}
  {{ $category := "Steel" }}
{{ else }}
  {{ $category := "Wood" }}
{{ end }}

{{ $filenameBeginning := $category }}

I also tried it putting .Params.category in quotes. Same result.

{{ if or ( eq ".Params.category" "Stairs") (in ".Param.category" "Stairs") }}
  {{ $category := "Stairs" }}
{{ else if or ( eq ".Params.category" "Steel") (in ".Param.category" "Steel") }}
  {{ $category := "Steel" }}
{{ else }}
  {{ $category := "Wood" }}
{{ end }}

{{ $filenameBeginning := $category }}

This gives me a server error on the last line saying that $category is undefined.
Please tell me what I am not getting here?
Thank you in advance!

Variables initialized ( := ) within a block are not available outside of the block.
Initialize ( := ) before the block, then assign ( = ) within the block.

{{ $foo := "" }}
{{ if true }}
  {{ $foo = "wibble" }}
{{ end }}
{{ $foo }}  --> wibble

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

4 Likes

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