58

how can I have multiple conditions in an if statement inside a template?

I tried this code:

{{ if .condition1 && .condition2 }}
    <!-- SHOW SOMETHING -->
{{ end }}

But it doesn't work. (in fact it panics)

Berry Jones
  • 857
  • 2
  • 7
  • 11

2 Answers2

91

You need to use function and, like:

{{ if and .condition1 .condition2 }}
<!-- SHOW SOMETHING -->
{{ end }}

Here's an working example: https://play.golang.org/p/g_itE5ggCM

shizhz
  • 11,715
  • 3
  • 39
  • 49
57
{{ if and (eq .var1 "8") (eq .var2 "9") (eq .var "10") }}
<!-- SHOW SOMETHING -->
{{ end }}

The parenthesis make the trick

kuisathaverat
  • 682
  • 5
  • 6
  • 2
    This answer is much more elaborated than the one from @shizhz, +1 – Odd May 10 '22 at 19:12
  • 1
    Thank you for this, I had the conditions with "and" but the more complex "eq" and "not" functions were not picking up the right parameters. The parenthesis are the important trick here! This should be the right answer. – OscarHanzely Sep 23 '22 at 20:43