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

Eleventy按数据集合年份字段生成独立页面的技术问询

按年份分组生成独立页面的解决方案

一、先在.eleventy.js中创建按年份分组的集合

首先需要把你的myData集合按Year字段分组,生成一个包含所有年份及对应数据的集合,替换你之前的oneYear集合代码:

eleventyConfig.addCollection("groupedByYear", function(collection) {
  // 获取_data文件夹里的myData完整集合
  const allItems = collection.getAll()[0].data.myData;
  
  // 用reduce方法按Year字段分组
  const groupedData = allItems.reduce((groups, item) => {
    const year = item.Year;
    // 若当前年份的分组不存在,初始化空数组
    if (!groups[year]) {
      groups[year] = [];
    }
    // 将当前数据项加入对应年份的分组
    groups[year].push(item);
    return groups;
  }, {});
  
  // 把分组后的对象转为数组(适配Eleventy分页需求)
  return Object.entries(groupedData).map(([year, items]) => ({
    year,
    items
  }));
});

二、用模板+分页自动生成每个年份的页面

创建一个模板文件(比如year.njk,也可用Liquid/Handlebars等你熟悉的模板引擎),通过Eleventy的分页功能自动为每个年份生成独立页面:

---
# 分页配置:基于groupedByYear集合生成页面
pagination:
  data: collections.groupedByYear
  size: 1          # 每个页面对应1个年份分组
  alias: yearGroup # 给当前分页项起别名,方便模板调用
permalink: "years/{{ yearGroup.year }}/" # 生成的页面URL路径,比如years/1901/
---

# {{ yearGroup.year }} 年的记录

<!-- 渲染当前年份的所有数据,可自定义样式 -->
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>姓名</th>
    </tr>
  </thead>
  <tbody>
    {% for item in yearGroup.items %}
    <tr>
      <td>{{ item.ID }}</td>
      <td>{{ item.First }} {{ item.Middle }} {{ item.Last }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

关键说明

  1. 为什么不用你之前的单年份集合?
    Eleventy的addCollection无法直接接收自定义参数(比如动态传入年份),所以必须先一次性完成全部分组,再通过分页功能批量生成页面。
  2. 运行效果:
    执行npx @11ty/eleventy构建后,会在_site/years/目录下生成每个年份的独立文件夹,每个文件夹里的index.html就是对应年份的页面。
  3. 兼容调整:
    如果你的Year字段存在格式不一致(比如混合数字/字符串),可以在分组前统一格式(比如const year = String(item.Year)),避免分组错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:52:33