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

Django custom template tag sort long list of '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"

我建议您在 .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",
    ...
}

只需将所有内容放入字典(查找 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]

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