Template variables direct boolean casting with if-statements

I just dived into an issue where I would like to assign an if condition to get a boolean stored in a certain variable. While I struggled receiving errors and had to make a dirty workaround.

What I’ve tried to do as I’m familiar with other Languages like PHP or JavaScript:

$year := 2004
$isLeapYear := (if eq (mod $year 4) 0)

But obviously this resulted in some errors so I did a workaround using $.Scratch.

{{ $.Scratch.Set "isLeapYear" false }}

{{ if eq (mod $year 4) 0 }}
    {{ $.Scratch.Set "isLeapYear" true }}
{{ end }}

{{ $isLeapYear := $.Scratch.Get "isLeapYear" }}

Which worked fine. But looks not like it is the right way to do it.

Appreviate any help or inputs to improve this statement :slightly_smiling:

The if doesn’t return anything, but I assume this works:

$isLeapYear := (modBool $year 4)
1 Like

Thanks a lot. This helped me out in this case.

I’m just curious if ternaries are available also?

For Example:

{{ $value := 5 }}
{{ $testTernary := (if lt $value 10) ? delimit (slice 0 $value) "" : $value }}

or something similar?

1 Like

The short answer is no.

Long answer: The Go templates aren’t “full Go language syntax” – but ternaries isn’t available in “regular Go” either, which is one of the things I miss from other languages. So there are lots if small if/else in Go programs.

Obviously not exactly what you’re asking for, but maybe there are times where default can provide convenience for you…


@rdwatters - indeed default would fit well in this case. I always wondered when this default function should be useful and forgot about it - thanks for re-enlightening :slight_smile:

1 Like