您也许可以使用Eleventy custom collections 来做您想做的事。我们可以在.eleventy.js文件中使用Javascript来统计每个标签的帖子数,然后按照帖子数对数据进行排序。
由于 Eleventy 似乎没有给我们一个预先分组的标签和帖子对象,我们正在自己做。这确实意味着,如果您在一篇文章上放置重复的标签,它将被计算两次。可以对标签进行重复数据删除,但如果你小心的话,这应该不是问题。
// .eleventy.js
module.exports = function (eleventyConfig) {
// ...
// addCollection receives the new collection's name and a
// callback that can return any arbitrary data (since v0.5.3)
eleventyConfig.addCollection('bySize', (collectionApi) => {
// see https://www.11ty.dev/docs/collections/#getall()
const allPosts = collectionApi.getAll()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
const countPostsByTag = new Map()
allPosts.forEach((post) => {
// short circuit eval sets tags to an empty array if there are no tags set
const tags = post.data.tags || []
tags.forEach((tag) => {
const count = countPostsByTag.get(tag) || 0
countPostsByTag.set(tag, count + 1)
})
})
// Maps are iterators so we spread it into an array to sort
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
const sortedArray = [...countPostsByTag].sort((a, b) => b[1] - a[1])
// this function returns an array of [tag, count] pairs sorted by count
// [['bonfires', 4], ['books', 3], ['boats', 2], ...]
return sortedArray
})
})
return {
// ...
}
}
然后我们可以通过collections.bySize 在 Nunjucks 中使用这些数据。
<section id="tags-number-of-posts">
{# we can still destructure the tag name and count even though it's an array #}
{% for tag, count in collections.bySize %}
{% set tagUrl %}/tags/{{ tag | slug }}/{% endset %}
<a href="{{ tagUrl | url }}">{{ tag }} ({{ count }})</a><br/>
{% endfor %}
</section>
如果您需要在集合对象中包含帖子数组而不仅仅是帖子数量,也可以修改 JavaScript 来实现。