我有一个简单的11站点v0.11.0
我在前面的内容中使用标签来生成集合。
例如:
---
title: Some post
tags:
- apple
- banana
- soccer
---我想显示每个标签/集合的列表,但我不知道如何做到这一点。
发布于 2021-02-07 07:35:29
我可以通过在我的.eleventy文件中创建一个新的集合来让它工作...
eleventyConfig.addCollection("tagsList", function(collectionApi) {
const tagsList = new Set();
collectionApi.getAll().map( item => {
if (item.data.tags) { // handle pages that don't have tags
item.data.tags.map( tag => tagsList.add(tag))
}
});
return tagsList;
});然后在模板中:
{% for tag in collections.tagsList %}
<a href="/tags/{{tag}}">{{tag}}</a>
{% endfor %}但这感觉很麻烦,我怀疑一定有更好的方法来做到这一点。
发布于 2021-02-13 23:29:01
你自己的答案在我看来是相当正确的。一些评论:
addGlobalData()方法创建custom global data,但是像访问collection (collections.tagsList)一样访问数据。addGlobalData())的另一种方法是创建一个集合(addCollection())。这就是我在我的第11个网站上做的事情:I create a collection of tags in my .eleventy.config.js。看起来11ty/eleventy-base-blog also uses a collection of tags.Array.prototype.map()返回了一个新的数组。您的代码使用了两次map(),但没有使用它们的返回值(即新数组)。如果不需要新阵列,使用Array.prototype.forEach()会更有意义。下面是我如何创建集合(与您的解决方案非常相似):
config.addCollection('tagsList', (collectionApi) => {
const tagsSet = new Set()
collectionApi.getAll().forEach((item) => {
if (!item.data.tags) return
item.data.tags.forEach((tag) => tagsSet.add(tag))
})
return tagsSet
})模板中的用法将是相同的。
额外功能:具有过滤功能(不包括标签"foo“和"bar")和字母排序:
config.addCollection('tagsList', (collectionApi) => {
const tagsSet = new Set()
collectionApi.getAll().forEach((item) => {
if (!item.data.tags) return
item.data.tags
.filter((tag) => !['foo', 'bar'].includes(tag))
.forEach((tag) => tagsSet.add(tag))
})
return [...tagsSet].sort((a, b) => b.localeCompare(a))
})发布于 2022-01-10 21:32:56
我的工作代码版本
// Display tag list on page
eleventyConfig.addCollection('tagsList', function (collectionApi) {
const tagsList = new Set()
collectionApi.getAll().map((item) => {
if (item.data.tags) {
// handle pages that don't have tags
item.data.tags.filter((tag) => !['yourtag'].includes(tag)).map((tag) => tagsList.add(tag))
}
})
return tagsList
})https://stackoverflow.com/questions/66083103
复制相似问题