Eleventy中如何将文章作者关联到作者简介数据
解决Eleventy中作者Key与Contributors数据关联的问题
核心优化思路
先把contributors.json的数据和作者文章集合整合,让分页时能直接拿到完整的作者信息,同时优化页面里的作者匹配逻辑,解决标题显示和数据关联的问题。
1. 重构作者集合,整合完整数据
修改.eleventy.js,先导入contributors.json并转成key索引的对象,再重构authorList集合,返回包含作者完整信息和对应文章的数组:
const contributors = require('./contributors.json'); // 把contributors转成key为键的对象,方便快速查找 const contributorLookup = contributors.reduce((acc, curr) => { acc[curr.key] = curr; return acc; }, {}); // 重构authorList集合 eleventyConfig.addCollection('authorList', collection => { const authorPostsMap = {}; // 遍历所有文章,按作者key分组 collection.getAll().forEach(post => { if (!post.data.authors) return; post.data.authors .filter(authorKey => !['posts', 'all'].includes(authorKey)) .forEach(authorKey => { if (!authorPostsMap[authorKey]) { authorPostsMap[authorKey] = []; } authorPostsMap[authorKey].push(post); }); }); // 转换为包含完整作者信息的数组 return Object.entries(authorPostsMap).map(([key, posts]) => { // 找不到对应作者时用key作为姓名兜底 const authorInfo = contributorLookup[key] || { key, name: key }; return { ...authorInfo, posts: posts }; }); });
2. 修改作者页面Frontmatter,显示真实姓名
调整authors.njk的Frontmatter,分页数据源换成新的authorList,此时author变量就是包含完整信息的对象,直接用author.name生成标题:
layout: base.njk permalink: /authors/{{ author.key | slugify }}/ pagination: data: collections.authorList size: 1 alias: author eleventyComputed: title: Posts written by {{ author.name }} summary: "All posts written by “{{ author.name }}”"
3. 优化作者页面内容,展示简介与关联文章
现在author已经是完整的作者对象,直接用它展示顶部简介;文章循环里直接用当前作者的信息生成链接即可:
<!-- 页面顶部展示作者简介 --> <div class="author-profile"> <img src="{{ author.img.url }}" alt="{{ author.img.alt }}" class="author-avatar"> <h1>{{ author.name }}</h1> <!-- 这里可以添加作者的其他信息,比如简介、邮箱等 --> </div> <h2>Showing {{ author.posts.length }} posts</h2> <ul class="cards"> {%- for post in author.posts | reverse -%} <li class="card__item"> <article> <h3 class="card__title"><a href="{{ post.url }}" class="card__link">{{ post.data.title }}</a></h3> <span class="card__author-name"> <a href="/authors/{{ author.key | slugify }}" class="card__author-link">{{ author.name }}</a> </span> <!-- 其他文章内容,比如摘要、日期等 --> </article> </li> {%- endfor %} </ul>
可选:添加全局作者查找过滤器
如果需要在文章详情页等其他页面快速获取作者信息,在.eleventy.js里加个过滤器:
eleventyConfig.addFilter('getAuthor', (authorKey) => { return contributorLookup[authorKey] || { key: authorKey, name: authorKey }; });
在文章页使用示例:
{% set postAuthor = post.data.authors[0] | getAuthor %} <p>作者:<a href="/authors/{{ postAuthor.key | slugify }}">{{ postAuthor.name }}</a></p>
问题根源说明
- 原来的
authorList只返回了作者key和对应文章的映射,分页时拿到的author是字符串key,自然无法获取真实姓名; - 原
authors.njk里的匹配逻辑有误:比如用post.data.author(应该是post.data.authors[0]),还有contributor[0]的错误写法,导致无法正确关联作者数据。
内容的提问来源于stack exchange,提问作者Daz Lee
相关产品推荐
相关产品推荐

