如何在11ty中使用getAllSorted()限制自定义集合仅返回文章?
问题
我在11ty中创建了如下自定义集合:
eleventyConfig.addCollection("recentPosts", function(collection) { return collection.getAllSorted().reverse().slice(0, 3); });
我希望仅返回文章,按逆时间顺序排序并显示最新的三篇。当前代码运行正常,但getAllSorted()会返回所有内容而非仅文章。我的输出如下:
<ul> <li><a href="/_dist/index-bak/"></a></li> <li><a href="/_dist/posts/important-fourth-post-20230711/"></a></li> <li><a href="/posts/important-fourth-post-20230711/">The all important fourth post</a></li> </ul>
可见它获取的是最新修改的三条内容,而非仅文章集合,请问如何修改以仅返回文章?
解决方案
你需要在集合中过滤出仅属于文章的内容,11ty里可以通过两种常见方式实现:
方法1:通过文件路径过滤(假设文章都存放在posts目录)
修改集合代码,先筛选路径包含posts的内容,再排序取前3:
eleventyConfig.addCollection("recentPosts", function(collection) { return collection.getAllSorted() .reverse() .filter(item => item.inputPath.includes("/posts/")) .slice(0, 3); });
方法2:通过Front Matter字段过滤(假设文章Front Matter定义了type: post)
如果你的文章在Front Matter中设置了专属标识(比如type: post或layout: post),可以直接匹配该字段:
eleventyConfig.addCollection("recentPosts", function(collection) { return collection.getAllSorted() .reverse() .filter(item => item.data.type === "post") .slice(0, 3); });
补充说明
getAllSorted()默认按文件修改时间排序,反转后即可得到最新内容在前的顺序- 过滤条件可根据你的项目实际结构调整,比如用
item.data.layout === "post"匹配文章布局
内容的提问来源于stack exchange,提问作者River
相关产品推荐
相关产品推荐

