11ty博客使用njk模板如何按图书名称首字母分组展示内容
方案1:优先推荐,在Eleventy配置中预处理分组(模板逻辑更简洁)
首先在你的.eleventy.js配置文件中新增一个预分组的自定义集合:
// .eleventy.js module.exports = function(eleventyConfig) { eleventyConfig.addCollection("groupedBooks", function(collectionApi) { const allBooks = collectionApi.getFilteredByTag("books"); const bookGroups = {}; allBooks.forEach(book => { // 取书名首字母统一转大写,避免大小写导致的分组错误 const firstLetter = book.data.name.trim().charAt(0).toUpperCase(); if (!bookGroups[firstLetter]) { bookGroups[firstLetter] = []; } bookGroups[firstLetter].push(book); }); // 按字母顺序排序分组后返回 return Object.keys(bookGroups).sort().map(letter => ({ groupLetter: letter, bookList: bookGroups[letter] })); }); // 你原有的其余配置保持不变 };
之后直接在njk模板中遍历已分组的集合即可:
<div> {% for group in collections.groupedBooks %} <h2>{{ group.groupLetter }}</h2> {% for book in group.bookList %} <a class="book" href="{{ book.url }}"> <article> <h3 class="text-link"> {{ book.data.name }} </h3> <p>{{ book.data.text }}</p> </article> </a> {% endfor %} {% endfor %} </div>
方案2:无需修改配置,直接在NJX模板中实现分组
如果你不想调整Eleventy配置,也可以直接在模板中通过变量比对首字母实现,注意先对图书列表按书名排序:
<div> {# 先按书名对所有图书排序,保证同首字母的图书集中展示 #} {% set sortedBooks = collections.books | sort(attribute="data.name") %} {% set prevLetter = "" %} {% for book in sortedBooks %} {% set currentLetter = book.data.name.trim().charAt(0).toUpperCase() %} {% if currentLetter != prevLetter %} <h2>{{ currentLetter }}</h2> {% set prevLetter = currentLetter %} {% endif %} <a class="book" href="{{ book.url }}"> <article> <h3 class="text-link"> {{ book.data.name }} </h3> <p>{{ book.data.text }}</p> </article> </a> {% endfor %} </div>
注意:你原有代码中多余了一个无对应
{% if %}的{% endif %},使用上述代码时可以直接替换原有逻辑。
内容的提问来源于stack exchange,提问作者Oleksii Binetskyi
相关产品推荐
相关产品推荐

