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

如何修改Jekyll主题代码实现标签按关联文章数量而非字母顺序排序

修改方法

你现有代码的前四行是实现标签按字母排序的逻辑,直接替换这部分为按关联文章数量排序的逻辑即可:

  1. 删掉原有前4行的标签字母序处理代码:
{% capture site_tags %}{% for tag in site.tags %}{{ tag | first | downcase }}{{ tag | first }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' | sort %}
{% capture site_tags %}{% for tag in site_tags %}{{ tag | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' %}
  1. 替换为以下按文章数量倒序排序的代码:
{% capture site_tags %}{% for tag in site.tags %}{{ site.tags[tag.first] | size | minus: 1000000 }}{{ tag | first }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' | sort %}
{% capture site_tags %}{% for tag in site_tags %}{{ tag | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' %}

原理说明:这里用文章数减去一个远大于网站总文章数的固定值,得到负数,排序后文章数越多的负数越小,排在越靠前的位置,自然实现按文章数从多到少排序。如果需要按文章数从少到多排序,把minus: 1000000去掉即可。

  1. 剩余代码保持不变,原来的标签大小样式计算、渲染逻辑都可以正常复用。

完整修改后代码

{% capture site_tags %}{% for tag in site.tags %}{{ site.tags[tag.first] | size | minus: 1000000 }}{{ tag | first }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' | sort %}
{% capture site_tags %}{% for tag in site_tags %}{{ tag | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' %}

{% assign post_count = site.posts | size %}
{% capture tag_counts %}{% for tag in site_tags %}{{site.tags[tag] | size | times: 10 | plus: post_count | minus: 1 | divided_by: post_count }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign tag_counts = tag_counts | split: ',' %}

<ul class="tags quick-links">
{% for tag in site_tags %}
    {% assign tag_data = site.data.tags[tag] %}
    {% capture tag_classes %}tag tag-size-{{ tag_counts[forloop.index0] }} tag-{{ tag | slugify }}{% endcapture %}
    {% capture tag_name %}{% if tag_data.title %}{{ tag_data.title }}{% else %}{{ tag }}{% endif %}{% endcapture %}
    <li><a href="{{ include.baseurl }}#{{ tag | slugify }}" class="{{ tag_classes }}">{{ tag_name }}<span class="count">{{ site.tags[tag] | size }}</span></a></li>
{% endfor %}
</ul>

内容的提问来源于stack exchange,提问作者K. Sreeman Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:27:04