skip to Main Content

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


    • from what i understood this is a possible solution:
    <button class="{{ or (and (eq .var1 "val123") "active") }} class1 class2 class3 class4 class5 class6 ...">
        test
    </button>
    
    Login or Signup to reply.
  1. 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:

    <button class="{{ if eq .var1 "val123" }}active {{ end }}class1 class2 class3 class4 class5 class6 ......">test</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search