You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask的Jinja2模板if块中为不同数值的词条设置不同背景色

实现方案
  • 第一步:修改Jinja2模板代码
    你当前的terms已经变为(词条文本, 计数值)格式的元组列表,需要在遍历时解包两个值,为每个词条单独绑定对应计数类:
{% if terms|length > 1 %}
    <!-- 外层容器可保留自定义样式 -->
    <div class="term-wrapper">
        {% for term_text, count in terms %}
            <!-- 每个词条单独用行内元素包裹,绑定对应计数类 -->
            <span class="term term-count-{{ count }}">
                {{ term_text }}&nbsp;&nbsp;
            </span>
        {% endfor %}
    </div>
{% endif %}
  • 第二步:微调CSS规则(可根据实际类名适配)
    你已经添加的term-count-*规则可以直接复用,调整选择器匹配词条使用的元素即可,如果你用<span>包裹词条,修改为如下规则即可:
/* 保留默认样式作为兜底 */
.term {
    background-color: mintcream;
    /* 可添加内边距让背景显示更美观 */
    padding: 2px 4px;
    border-radius: 3px;
}
.term.term-count-1 {
    background-color: green;
}
.term.term-count-2 {
    background-color: lightblue;
}
.term.term-count-3 {
    background-color: deepskyblue;
}
.term.term-count-4 {
    background-color: blueviolet;
}
  • 效果说明
    遍历渲染时每个词条会自动匹配对应计数值的背景色,优先级更高的计数类样式会自动覆盖默认的mintcream背景色,无需额外逻辑判断。

内容的提问来源于stack exchange,提问作者marlon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:15:03