Conditional Variables

Is there a way to conditionalize variables similar to the following:

‘’’
{{ if eq .Page.Params.type “featured-artists” }}
{{ $artistName := .Page.Params.Title }}
{{ $artistURL := .Page.Params.artistURL }}
{{ else }}
{{ $artistName := .Page.Params.jurorGuestName }}
{{ $artistURL := .Page.Params.jurorGuestURL }}

{{ end }}
‘’’

This ability would greatly DRY out a lot of my code

Thnx

Yes. Initialize with := before the conditional block, and assign with = within the conditional block.

{{ $a := 0 }}
{{ if true }}
  {{ $a = 6 }}
{{ else }}
  {{ $a = 7 }}
{{ end }}
{{ $a }} --> 6
1 Like

Interesting, I thought for giggles to try out Bard, Googles Ai that now can answer coding questions and this is the answer given:

…you can use the cond function to conditionally assign values to variables. The cond function takes three arguments: a condition, a value to return if the condition is true, and a value to return if the condition is false.

In your case, the condition would be whether the type parameter is equal to "featured-artists". If it is, then the value of the artistName and artistURL variables would be set to the values of the Title and artistURL parameters, respectively. Otherwise, the values of the artistName and artistURL variables would be set to the values of the jurorGuestName and jurorGuestURL parameters, respectively.

Here is the code:

{{ $artistName := cond (eq .Page.Params.type "featured-artists") .Page.Params.Title .Page.Params.jurorGuestName }}

{{ $artistURL := cond (eq .Page.Params.type "featured-artists") .Page.Params.artistURL .Page.Params.jurorGuestURL }}

This code would assign the following values to the artistName and artistURL variables:

  • artistName = Title if the type parameter is equal to "featured-artists"
  • artistName = jurorGuestName if the type parameter is not equal to "featured-artists"
  • artistURL = artistURL if the type parameter is equal to "featured-artists"
  • artistURL = jurorGuestURL if the type parameter is not equal to "featured-artists"

You can then use the artistName and artistURL variables in your template as you would any other variable.

Not bad! Maybe send RP coding question to Bard first? LOL

@jmooring

The problem you can run into with the cond function is that it can only evaluate boolean values (true or false). It cannot evaluate other truthy or falsy values.

{{ warnf "%s" (cond 42 "6" "7") }}

Error ... executing "main" at <42>: expected bool; found 42
1 Like