Matrix Twig循环行:实现交替指定颜色的技术求助
解决Twig循环行颜色周期重复的问题
我来帮你搞定这个循环配色的需求!你想要的是一个4行重复的周期规律:white → gray → white → navy,然后无限循环下去。你的现有代码只针对前5行做了判断,所以没法实现持续循环,我们可以利用Twig的模运算(%)来完美实现这个周期逻辑。
方案一:直接基于4行周期的模运算判断
这是最直观的实现方式,通过计算当前行索引对4取余的结果,来匹配对应的颜色:
{% set cycle_remainder = loop.index % 4 %} {% if cycle_remainder == 1 or cycle_remainder == 3 %} <div id="{{ target }}" class="band white"> {% elseif cycle_remainder == 2 %} <div id="{{ target }}" class="band gray"> {% else %} {# 余数为0时,对应第4、8、12...行 #} <div id="{{ target }}" class="band navy"> {% endif %}
逻辑解释:
loop.index % 4会得到1、2、3、0的循环结果,正好对应4行一个周期:- 余数1 → 第1、5、9...行 → white
- 余数2 → 第2、6、10...行 → gray
- 余数3 → 第3、7、11...行 → white
- 余数0 → 第4、8、12...行 → navy
方案二:先区分奇偶行再细化偶数行
因为所有奇数行都是white,我们可以先判断奇偶,再对偶数行做细分,这样代码可读性更强:
{% if loop.index is odd %} <div id="{{ target }}" class="band white"> {% else %} {% set even_cycle = loop.index % 4 %} {% if even_cycle == 2 %} <div id="{{ target }}" class="band gray"> {% else %} <div id="{{ target }}" class="band navy"> {% endif %} {% endif %}
逻辑解释:
- 所有奇数行直接应用white样式;
- 偶数行里,第2、6、10...行(
loop.index%4=2)用gray,第4、8、12...行(loop.index%4=0)用navy,完美匹配你的周期要求。
这两种方案都能实现无限循环的配色效果,不管你的列表有多少行,都会严格按照你想要的规律渲染颜色。
内容的提问来源于stack exchange,提问作者Jon Packziński
相关产品推荐
相关产品推荐

