有没有一种方法可以从 site.posts 获取当前帖子的索引号?
{{ site.posts | size }} 是所有帖子的总数。 我需要的是类似于 {{ site.posts.index }} 或者 {{ page.index }} 的东西。
我正在尝试在每个帖子页面上显示一个计数器。例如:第43篇,共2654篇
在 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 }}
回答自己的问题,也许可以帮助其他人:
确实有另一种方法(而且没有明显的性能损失),可以使用一个简单的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 }}在模板中获取文章索引。