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

如何用Pug将按钮按每10个一组包裹进div?

纯Pug实现按钮按10个一组分组包裹

可以通过Pug内置的数组处理能力,不用额外JS就能实现分组。这里提供两种直观的写法:

方法一:用reduce拆分数组(更紧凑)

div#container
  each group, index in accounts.reduce((acc, curr, i) => {
    const groupIdx = Math.floor(i / 10);
    if (!acc[groupIdx]) acc[groupIdx] = [];
    acc[groupIdx].push(curr);
    return acc;
  }, [])
    div.button-group
      each account in group
        button= account.stuff

这段代码通过reduce把accounts数组拆成每10个元素一组的二维数组,外层遍历每个分组生成包裹div,内层遍历分组内的元素生成按钮。

方法二:用slice切片(更直观)

div#container
  - const groupCount = Math.ceil(accounts.length / 10);
  each _, groupIdx in Array(groupCount)
    div.button-group
      each account in accounts.slice(groupIdx * 10, (groupIdx + 1) * 10)
        button= account.stuff

先计算总分组数(向上取整),然后遍历每个分组,用slice截取对应范围的accounts元素,再生成按钮和包裹div。

为什么之前的取余方法会生成空div?

你之前尝试的取余逻辑,大概率是在遍历单个account时判断索引取余,这种方式容易出现div未正确闭合或重复生成的问题。上面两种方法都是先分组再渲染,从根源避免了空div的出现,完全符合纯Pug实现的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:35:03