Django 自定义模板标签排序长列表的"elif"



我有一个Django自定义模板标签,它根据输入的值更改字体的颜色。

一切都很好,但我想知道是否有一种更干净的方式来写这篇文章,而不是做所有这些elif语句。显示的甚至不是一半的球队,还有3个其他联盟的球队会被包括在这个标签中。

@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"

只需将所有内容放入字典(查找表(即可。

@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]

这既快速又清晰。如果团队不存在,您也可以使用return team_colors.get(team, default='no_color')来返回默认颜色。

我建议您在.json文件中列出所有团队及其所需的颜色,将其导入到视图中,并尝试使用以下方法捕捉颜色。

import json
def getTeamColor(team):
with open('file.json') as file:   # file contains teams and colors
team_colors = json.load(file)

for teams in tuple(team_colors.keys()):
if team in teams:
return team_colors[teams]

JSON文件应该是如下结构。

{
"('Celtics', 'Jazz')": "green",
"('Hawks', 'Bulls', 'Rockets')": "red",
"('Nets',)": "grey",
...
}

最新更新