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
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 }}
(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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With