I have a Django custom template tag that changes the color of a font depending on the value that is put in.
Everything works fine but I was wondering if there was a cleaner way of writing this instead of making all these elif
statements. Shown isn't even half of the teams, there are still 3 other leagues of teams that would be included in that tag.
@register.filter(name='teamColor')
def teamColor(team):
if team == "Celtics" or team == "Jazz":
return "green"
elif (team == "Hawks" or team == "Bulls" or team == "Rockets"
or team == "Pistons" or team == "Clippers" or team == "Heat" or
team == "Trail Blazers" or team == "Raptors"):
return "red"
elif team == "Nets":
return "grey"
elif (team == "Hornets" or team == "Lakers" or team == "Suns" or
team == "Kings"):
return "purple"
elif team == "Cavaliers":
return "#b11226"
elif team == "Mavericks" or team == "Grizzlies" or team == "76ers":
return "blue"
elif team == "Nuggets" or team == "Pacers":
return "yellow"
elif (team == "Warriors" or team == "Timberwolves" or team == "Thunder" or
team == "Knicks"):
return "#1D428A"
elif team == "Bucks":
return "#00471b"
elif team == "Pelicans":
return "gold"
elif team == "Magic":
return "#0077C0"
elif team == "Spurs" or team == "Wizards":
return "silver"
Simply put everything in a dictionary (look-up table).
@register.filter(name='team_color')
def team_color(team):
team_colors = {
'Celtics': 'green',
'Jazz': 'green',
'Hawks': 'red',
'Bulls': 'red',
'Rockets': 'red',
'Pistons': 'red',
'Clippers': 'red',
'Heat': 'red',
# ... etc ..
}
return team_colors[team]
This is both really fast and clear. And you can also use return team_colors.get(team, default='no_color')
instead to return a default color if the team doesn't exist.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments