You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jekyll中基于front matter标签查询相关页时如何排除当前页面

问题根源

你代码失效的核心原因是循环遍历站点页面时的变量名和Jekyll内置的当前页全局变量page重名了。你写的page.url == page.url本质是拿循环项的url和它自身做比较,结果永远为真,所以所有匹配标签的页面都被过滤掉了。

正确实现代码

你只需要修改循环变量名,避免命名冲突,再补充标签空格处理逻辑避免匹配失败即可:

{% assign current_page_tags = page.tags | split: "," | map: "strip" %}
<ul>
  {% for item in site.pages %}
    <!-- 先排除当前页面 -->
    {% if item.url != page.url %}
      <!-- 匹配最多3个标签的逻辑和你原有逻辑一致 -->
      {% if item.tags contains current_page_tags[0] or item.tags contains current_page_tags[1] or item.tags contains current_page_tags[2] %}
        <li><a href="{{ item.url }}">{{ item.title }}</a></li>
      {% endif %}
    {% endif %}
  {% endfor %}
</ul>

优化版本(推荐)

如果你希望不用硬编码匹配标签的数量,不管当前页设置多少个标签都能自动匹配有任意相同标签的页面,可以用标签交集判断:

{% assign current_page_tags = page.tags | split: "," | map: "strip" %}
<ul>
  {% for item in site.pages %}
    {% assign matched_tags = item.tags | split: "," | map: "strip" | intersect: current_page_tags %}
    {% if item.url != page.url and matched_tags.size > 0 %}
      <li><a href="{{ item.url }}">{{ item.title }}</a></li>
    {% endif %}
  {% endfor %}
</ul>

内容的提问来源于stack exchange,提问作者Liu Kang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:18:03