How to retrieve the current post index number in Jekyll?

点点圈 提交于 2019-12-10 20:51:41

问题


Is there a way to get the current post index number from site.posts?

{{ site.posts | size }} is the total number of posts. What I need is something like {{ site.posts.index }} or {{ page.index }}.

I am trying to display a counter on each post page. Example: Post 43 of 2654


回答1:


In a for loop you can get current item index in two ways :

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

or

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

And what you need is {{ forloop.index }}




回答2:


(Answering my own question, maybe it helps someone else)

There is indeed another way (and without a major performance hit) using a simple jekyll plugin:

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

Save as post_index_generator.rb and place in _plugins folder.

Get the post index in the template with {{ page.index }}



来源:https://stackoverflow.com/questions/26073090/how-to-retrieve-the-current-post-index-number-in-jekyll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!