如何在Jekyll中获取当前文章的索引编号?

7

有没有一种方法可以从 site.posts 获取当前帖子的索引号?

{{ site.posts | size }} 是所有帖子的总数。 我需要的是类似于 {{ site.posts.index }} 或者 {{ page.index }} 的东西。

我正在尝试在每个帖子页面上显示一个计数器。例如:第43篇,共2654篇

2个回答

12

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

{% for post in site.posts %}{{ forloop.index }}{% endfor %}
# will print 123...
或者
{% for post in site.posts %}{{ forloop.index0 }}{% endfor %}
# will print 012...

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


1
它能够工作,但是为了找到索引,每个帖子都要循环一遍,这样做太昂贵了,而且生成时间也变得不可接受。还有其他的想法吗?或者有没有办法在前置元数据中编程添加索引号呢? - deadelvis

6

回答自己的问题,也许可以帮助其他人:

确实有另一种方法(而且没有明显的性能损失),可以使用一个简单的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

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

使用{{ page.index }}在模板中获取文章索引。


对我来说似乎不起作用。有什么想法可以现代化它吗? - phatmann
自2014年以来,已经有了一种弃用的方法,尽管您的版本仍然可以正常工作,“Deprecation: posts.each_with_index should be changed to posts.docs.each_with_index.” - Csaba Toth
这个能在GitHub的gh-pages上工作吗?我是说自定义插件。 - Csaba Toth
对于 gh-pages:https://dev59.com/questions/_lQJ5IYBdhLWcg3wuob7 - Csaba Toth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接