Web Front-end
JS Tutorial
The correct implementation method in Svelte to avoid #each loop causing repeated display of related articles
The correct implementation method in Svelte to avoid #each loop causing repeated display of related articles

本文介绍如何在 Svelte 中正确筛选并去重展示“相关文章”,解决因嵌套 #each 导致同一文章被多次渲染的问题,核心是将标签匹配逻辑前置到 JavaScript 层完成过滤,而非在模板中双重遍历。
本文介绍如何在 Svelte 中正确筛选并去重展示“相关文章”,解决因嵌套 `#each` 导致同一文章被多次渲染的问题,核心是将标签匹配逻辑前置到 JavaScript 层完成过滤,而非在模板中双重遍历。
在构建博客类 Svelte 应用时,常需为当前文章动态展示“相关文章”——即标题不同、已发布、且至少共享一个标签的文章。若直接在模板中使用嵌套 {#each}(如外层遍历所有文章、内层遍历其标签),会导致同一候选文章因匹配多个共同标签而被重复渲染多次。例如:当前文章含 ["svelte", "tutorial"],而某篇候选文章也含这两个标签,则该文章会在 <ul> 中出现两次,严重破坏 UI 逻辑与用户体验。
根本原因在于:原始写法将筛选条件(是否相关)错误地放在了模板渲染阶段,且未做去重控制。正确的解法是——将筛选与去重完全交由 JS 逻辑处理,模板仅负责干净、线性的渲染。
以下是优化后的推荐实现:
<script>
import { getMarkdownPosts } from '$lib/utils/getPosts';
import { onMount } from 'svelte';
let relatedPosts = [];
export let currentPostTitle, currentPostTags;
onMount(async () => {
const allPosts = await getMarkdownPosts();
// ✅ 单次过滤:排除自身 + 未发布 + 无标签交集
relatedPosts = allPosts.filter(post => {
const { title, tags, published } = post.meta;
return (
title !== currentPostTitle &&
published === true &&
currentPostTags.some(tag => tags.includes(tag))
);
});
});
</script>
{#if relatedPosts.length > 0}
<h3>Related posts</h3>
<ul>
{#each relatedPosts as { slug, meta: { title } }}
<li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
{/each}
</ul>
{:else}
<p>No related posts found.</p>
{/if}
✅ 关键改进点说明:
- 逻辑前置:filterRelatedPosts() 被整合进 onMount,确保异步数据加载完成后立即执行一次精准过滤,返回唯一、无重复的 relatedPosts 数组;
- 语义清晰的筛选条件:使用 currentPostTags.some(tag => tags.includes(tag)) 判断「至少一个标签匹配」,避免内层循环;
- 模板极简渲染:{#each relatedPosts} 仅作单层遍历,天然杜绝重复;
- 健壮性增强:显式检查 published === true(而非仅 if (published)),避免 falsy 值误判;增加空状态提示,提升用户体验。
⚠️ 注意事项:
- 若 currentPostTags 或 post.meta.tags 可能为 null/undefined,应在 filter 中添加防御性检查(如 Array.isArray(currentPostTags) && Array.isArray(tags));
- 标签匹配默认区分大小写。如需忽略大小写,可改用 currentPostTags.some(tag => tags.map(t => t.toLowerCase()).includes(tag.toLowerCase()));
- 对于大型文章库(>100 篇),可进一步加入按匹配标签数或发布时间排序(如 .sort((a, b) => b.meta.tags.filter(t => currentPostTags.includes(t)).length - a.meta.tags.filter(...).length)),提升相关性。
此方案兼顾性能、可读性与可维护性,符合 Svelte “逻辑在脚本中,视图只负责呈现”的设计哲学,是生产环境推荐的标准实践。
The above is the detailed content of The correct implementation method in Svelte to avoid #each loop causing repeated display of related articles. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20570
7
13669
4
useEffect in MERN stack React application implements instant update of user information after login
Apr 04, 2026 am 06:57 AM
This tutorial deeply explores the problem of useEffect hook in the MERN stack React application. After the user logs in, the user information cannot be updated immediately, and the page needs to be refreshed to display the latest data. The article analyzes in detail the correct use of the useEffect dependency array, points out common errors, and provides a dependency management solution based on user status changes to ensure that user information can be responded to and updated immediately after logging in, thereby improving the user experience.
Dynamic data transfer and management within scripts in Node-RED UI templates
Apr 04, 2026 am 06:54 AM
This article aims to solve the problem in Node-RED UI templates that cannot directly use Mustache syntax to dynamically inject JavaScript code within tags. We will explain the root cause and provide two safe and effective solutions: one is to directly access the passed data through $scope.msg, and the other is to render the data into JavaScript variables through Mustache combined with the | json filter. In addition, the article will also discuss the practice of encapsulating UI templates into subflows (Subflow) to achieve template reuse and centralized management.
JavaScript form validation: use custom CSS classes for precise control
Apr 04, 2026 am 05:42 AM
This tutorial dives into how to achieve precisely controlled form validation using pure JavaScript and custom CSS classes, rather than relying on browser default pseudo-classes. This article will analyze in detail the difference in verification timing between input and change events, and provide an optimization solution that effectively solves the problems of lagging verification status update and inaccurate class name assignment by combining the change event and the checkValidity() method, thereby achieving more flexible and user-friendly real-time form feedback.
A complete solution for retaining the ability to scroll vertically while scrolling horizontally
Apr 05, 2026 am 08:31 AM
This article provides a robust horizontal scrolling JavaScript implementation that intelligently determines the scrolling direction and boundary status to ensure that users can not only slide to the right to browse the content, but also scroll up to return to the initial area at the top.
A deep understanding of JavaScript array loops and their potential risks
Apr 04, 2026 am 06:42 AM
This article aims to delve into the concept of looping arrays in JavaScript, its potential risks, and how to effectively avoid these problems. We'll clarify some common misunderstandings about looping arrays, show through code examples what situations can lead to infinite loops or stack overflows, and provide safe alternatives to help developers better understand and work with this type of data structure.
A complete solution on how to implement product variations (such as sizes) and inventory limits in Stripe
Apr 05, 2026 am 08:36 AM
Stripe's custom_fields are not suitable for product variant selection and inventory management; the correct approach is to create an independent Product/Price for each variant, and implement inventory verification, preemption and synchronization logic at the application layer.
How to correctly understand and pass the parent node parameter to safely delete nodes in a binary search tree
Apr 12, 2026 am 06:18 AM
This article deeply analyzes the key role of the parentNode parameter in the BST node deletion operation, and explains why the current node must be explicitly passed in as the parent node when calling remove() recursively instead of using null - this is related to whether the minimum node in the subtree can be accurately located and the link can be safely broken.
Storing Access Tokens in NextAuth Sessions: Security Considerations and Best Practices
Apr 07, 2026 am 08:42 AM
This article takes an in-depth look at the security and practices of storing access tokens in NextAuth sessions. By leveraging NextAuth's powerful JWT session strategy, access tokens are encrypted and securely managed. This article will provide detailed guidance on how to integrate custom authentication logic in NextAuth configuration, extend session data, and securely access these tokens on the client side. At the same time, key security best practices such as token rotation are emphasized to ensure the robustness and security of production-grade applications.





