Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the current post index number in Jekyll?

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

like image 719
deadelvis Avatar asked Sep 27 '14 09:09

deadelvis


2 Answers

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 }}

like image 189
David Jacquel Avatar answered Oct 07 '22 11:10

David Jacquel


(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 }}

like image 23
deadelvis Avatar answered Oct 07 '22 11:10

deadelvis