I a Golang web project, there’re templates with code like this:
<button
{{ if eq .var1 "val123" }}
class="active class1 class2 class3 class4 class5 class6 ......"
{{ else }}
class="class1 class2 class3 class4 class5 class6 ......"
{{ end }}
>
test
</button>
Is there a way to simplify it?
Can it be reduced to one line?
2
Answers
Yes, you can simplify the template code by using the ternary operator (also known as the conditional operator) to achieve the same result in one line. In Go templates, you can use the if and else constructs to create conditions, but you cannot use them on a single attribute line. However, the ternary operator can be used in place of the if-else to reduce the code to one line.
Here’s how you can achieve that: