如何在Django中根据变量值显示特定颜色?
完善Django模板中基于状态的样式设置
你可以借助Django模板的条件判断标签,根据application.status的不同值动态渲染对应的样式,完整代码如下:
<div> {% for application in object_list %} <div style="{% if application.status == 'rejected' %}background: gray; color: lightgrey{% elif application.status == 'accepted' %}background: green; color: lightgreen{% elif application.status == 'in progress' %}background: blue; color: lightblue{% endif %}"> <span>{{ application.status }}</span> </div> {% endfor %} </div>
样式对应规则:
- 当
application.status为rejected:应用background: gray; color: lightgrey - 当
application.status为accepted:应用background: green; color: lightgreen - 当
application.status为in progress:应用background: blue; color: lightblue
这种写法逻辑清晰,后续如果需要新增状态样式,直接添加新的{% elif %}分支即可,便于维护。
内容的提问来源于stack exchange,提问作者Drozon
相关产品推荐
相关产品推荐

