multiple conditions in if statement Go templates
Asked Answered
O

2

66

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)

Outmost answered 26/3, 2017 at 7:52 Comment(0)
H
99

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

Heterothallic answered 26/3, 2017 at 8:16 Comment(0)
C
71
{{ if and (eq .var1 "8") (eq .var2 "9") (eq .var "10") }}
<!-- SHOW SOMETHING -->
{{ end }}

The parenthesis make the trick

Cnut answered 13/7, 2021 at 11:34 Comment(2)
This answer is much more elaborated than the one from @shizhz, +1Ascot
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.Chichihaerh

© 2022 - 2024 — McMap. All rights reserved.