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

如何通过代码编程创建Eleventy(11ty)自定义集合

Eleventy 原生支持编程式自定义集合,完全不需要依赖 frontmatter 中的 tags 字段,所有逻辑都可以在项目根目录的 .eleventy.js 配置文件中编写,以下是对应两个需求的具体实现方式。

实现代码

所有集合定义都写在配置文件的导出函数中,你可以根据自己的项目实际路径调整文件匹配规则。

// .eleventy.js 配置文件
module.exports = function(eleventyConfig) {
  // 1. 按status字段生成对应状态的文章集合
  // 方式一:生成按状态分组的集合对象,包含所有状态的文章
  eleventyConfig.addCollection("postsGroupedByStatus", function(collectionApi) {
    // 替换成你项目中实际的文章文件路径匹配规则
    const allPosts = collectionApi.getFilteredByGlob("./src/posts/**/*.md");
    const groupMap = {};
    allPosts.forEach(post => {
      // 读取frontmatter中的status字段,未设置的默认归为草稿分组
      const currentStatus = post.data.status || "draft";
      if (!groupMap[currentStatus]) groupMap[currentStatus] = [];
      groupMap[currentStatus].push(post);
    });
    return groupMap;
  });

  // 方式二:单独生成指定状态的集合,比如直接拿所有“审核中”的文章
  eleventyConfig.addCollection("postsUnderReview", function(collectionApi) {
    return collectionApi.getFilteredByGlob("./src/posts/**/*.md")
      .filter(post => post.data.status === "审核中");
  });

  // 2. 生成距审核日期不足1个月的待审核文章集合
  eleventyConfig.addCollection("postsPendingAnnualAudit", function(collectionApi) {
    const allPosts = collectionApi.getFilteredByGlob("./src/posts/**/*.md");
    const now = Date.now();
    // 精准计算1个自然月后的时间,不需要精准自然月可以替换为 30*24*60*60*1000 的固定30天逻辑
    const nowDate = new Date();
    const oneMonthLater = new Date(nowDate.getFullYear(), nowDate.getMonth() + 1, nowDate.getDate()).getTime();
    
    return allPosts.filter(post => {
      // 跳过未配置下一次审核日期字段的文章,你可以把nextAuditDate替换成自己项目里用的字段名
      if (!post.data.nextAuditDate) return false;
      const auditTime = new Date(post.data.nextAuditDate).getTime();
      // 筛选出审核日期在未来1个月内的文章
      return auditTime > now && auditTime <= oneMonthLater;
    });
  });

  // 剩下的原有配置保持不变
  return {
    // 你的原有Eleventy配置项,比如目录规则、模板引擎配置等
  }
};
使用说明
  • 自定义集合和依赖tags生成的集合用法完全一致,在模板中直接通过 collections.集合名 即可访问对应内容,比如在模板里循环 collections.postsUnderReview 就能渲染所有审核中的文章
  • 夜间定时构建任务不需要额外做特殊适配,代码会自动读取构建运行时的系统时间计算日期差,每次构建都会自动更新待审核文章集合的内容
  • 你可以根据自己的业务逻辑任意调整筛选规则,比如增加文章分类、发布时间等判断条件,没有额外的限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:18:19