0
votes

My template looks like this currently:

{{range .Users}}
<div ...>
   <div class="row XXXX">
</div>
{{end}}

The XXX has to be replaced with a css-class that is based on a property of the User struct, UserLevel which is a string.

So depending on the value of UserLevel, I will display the correct css class:

UserLevel is "beg" then I need to output "beginner". UserLevel is "int" then I need to output "intermediate" etc.

I know I can just rename the css class to match the value of the property, but I don't want to keep a tight coupling between the 2.

Is this possible to do somehow since expressions are not allowed in if statements?

1

1 Answers

1
votes

There are several ways to do that, I will cover two. First way is to work with if statements and equality tests in the template:

{{range $count, $user := .Users}}
<div ...>
   <div class="row {{if eq $user.UserLevel "beg"}}beginner{{else if eq $user.UserLevel "int" }}intermediate{{else}}default{{end}}">
</div>
{{end}}

The second way is to define a function for the User, which outputs the correct class based on the UserLevel property:

func (u User) CssClass() string {
    switch u.UserLevel {
    case "beg":
        return "beginner"
    case "int":
        return "intermediate"
    default:
        return ""
    }
}

{{range $count, $user := .Users}}
<div ...>
   <div class="row {{$user.CssClass}}">
</div>
{{end}}

I put this little test code in the Go playground, both produce the same output with the correct class.