如何在Jekyll中检索当前的帖子索引号?

dea*_*vis 3 ruby liquid jekyll

有没有办法从site.posts获取当前的帖子索引号?

{{site.posts | size}}是帖子的总数.我需要的是{{site.posts.index}}{{page.index}}.

我想在每个帖子页面上显示一个计数器.示例:2654年第43期

Dav*_*uel 8

for循环中,您可以通过两种方式获取当前项索引:

{% for post in site.posts %}{{ forloop.index }}{% endfor %}
# will print 123...
Run Code Online (Sandbox Code Playgroud)

要么

{% for post in site.posts %}{{ forloop.index0 }}{% endfor %}
# will print 012...
Run Code Online (Sandbox Code Playgroud)

而你需要的是 {{ forloop.index }}


dea*_*vis 5

(回答我自己的问题,也许它可以帮助其他人)

使用简单的jekyll插件确实有另一种方式(并且没有重大的性能损失):

module Jekyll
    class PostIndex < Generator
        safe true
        priority :low
        def generate(site)
            site.posts.each_with_index do |item, index|
                item.data['index'] = index
            end
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

保存为post_index_generator.rb并放在_plugins文件夹中.

使用{{page.index}}在模板中获取帖子索引