本文介绍基于 Jekyll 的站点,怎么实现对站内所有标签进行分页列表展示。阅读本文前,建议先预读了解《Jekyll 插件 - 文章分页》。

插件实现思路

实现插件逻辑代码

laijinman-tag-list-page-generator.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
module Laijinman
    class TagListPageGenerator < Jekyll::Generator
        safe true
        
        def generate(site)
            paginate = site.config['paginate'] || 10;
            dir      = 'tags'
            layout   = 'tags'
            
            pre_page = paginate.to_i
            
            if site.layouts.key? layout
                total_tags = site.tags.size
                total_pages = total_tags.fdiv(pre_page).ceil
                
                tags = Array.new
                site.tags.each { |tag, posts|
                    data = Hash["tag" => tag, "posts" => posts]
                    tags.push(data)
                }
                
                for page in 1..total_pages
                    paginator = Paginator.new(tags, pre_page, page, dir)
                    
                    data = Hash.new()
                    data['paginator'] = paginator
                    site.pages << Page.new(site, paginator.page_path, data, layout)
                end
            end
        end
    end
end

页面渲染

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{%- if page.records.size > 0 -%}
<ul class="post-list tag-post-list">
  {% for item in page.records %}
  <li>
    <h3>
            <a class="post-link" href="/tag/{{ item.tag | escape }}">{{ item.tag | escape }}</a>
    </h3>
    <ul>
      {% assign posts=item.posts | slice: 0, 10 %}
      {% for post in posts %}
      <li><a href="{{ post.url | escape | relative_url }}">{{ post.title | escape }}</a></li>
      {% endfor %}
    </ul>
    <a href="/tag/{{ item.tag | escape }}"><i class="fa fa-folder" aria-hidden="true"></i> {{ item.posts.size }}</a>
  </li>
  {% endfor %}
</ul>
{%- endif -%}

演示

  • 标签 本站的标签列表。

相关链接