From 447c353a5d627b07a9d62b793a5a2ca10dac74e0 Mon Sep 17 00:00:00 2001 From: tangly1024 Date: Mon, 21 Mar 2022 17:32:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=8E=A8=E8=8D=90=E6=96=87?= =?UTF-8?q?=E7=AB=A0=E6=95=B0=E9=87=8F=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blog.config.js | 1 + pages/article/[slug].js | 39 +++++++++++++++++++++++---------------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/blog.config.js b/blog.config.js index 0b62db37..312d4603 100644 --- a/blog.config.js +++ b/blog.config.js @@ -26,6 +26,7 @@ const BLOG = { POST_LIST_STYLE: 'page', // ['page','scroll] 文章列表样式:页码分页、单页滚动加载 POST_LIST_PREVIEW: process.env.NEXT_PUBLIC_POST_PREVIEW || 'false', // 是否在列表加载文章预览 POST_PREVIEW_LINES: 12, // 预览博客行数 + POST_RECOMMEND_COUNT: 6, // 推荐文章数量 POSTS_PER_PAGE: 6, // post counts per page POSTS_SORT_BY: 'notion', // 排序方式 'date'按时间,'notion'由notion控制 diff --git a/pages/article/[slug].js b/pages/article/[slug].js index 9eb1bd65..e3f71f51 100644 --- a/pages/article/[slug].js +++ b/pages/article/[slug].js @@ -51,7 +51,7 @@ export async function getStaticProps ({ params: { slug } }) { const prev = allPosts.slice(index - 1, index)[0] ?? allPosts.slice(-1)[0] const next = allPosts.slice(index + 1, index + 2)[0] ?? allPosts[0] - const recommendPosts = getRecommendPost(post, allPosts) + const recommendPosts = getRecommendPost(post, allPosts, BLOG.POST_RECOMMEND_COUNT) return { props: { @@ -76,25 +76,32 @@ export async function getStaticProps ({ params: { slug } }) { * @param {*} count * @returns */ -function getRecommendPost (post, allPosts, count = 5) { - let filteredPosts = [] - for (const i in allPosts) { +function getRecommendPost (post, allPosts, count = 6) { + let recommendPosts = [] + const postIds = [] + const currentTags = post.tags + for (let i = 0; i < allPosts.length; i++) { const p = allPosts[i] - filteredPosts.push(Object.assign(p)) + if (p.id === post.id || p.type.indexOf('Post') < 0) { + continue + } + + for (let j = 0; j < currentTags.length; j++) { + const t = currentTags[j] + if (postIds.indexOf(p.id) > -1) { + continue + } + if (p.tags && p.tags.indexOf(t) > -1) { + recommendPosts.push(p) + postIds.push(p.id) + } + } } - if (post.tags && post.tags.length) { - const currentTag = post.tags[0] - filteredPosts = filteredPosts.filter( - p => p && p.slug !== post.slug && p.tags && p.tags?.includes(currentTag) && p.type === ['Post'] - ) + if (recommendPosts.length > count) { + recommendPosts = recommendPosts.slice(0, count) } - - // 筛选前5个 - if (filteredPosts.length > count) { - filteredPosts = filteredPosts.slice(0, count) - } - return filteredPosts + return recommendPosts } export default Slug