【发布时间】:2014-09-27 09:06:33
【问题描述】:
有没有办法从 site.posts 获取当前的帖子索引号?
{{ site.posts | size }} 是帖子的总数。 我需要的是 {{ site.posts.index }} 或 {{ page.index }}。
我正在尝试在每个帖子页面上显示一个计数器。示例:发布 43 of 2654
【问题讨论】:
有没有办法从 site.posts 获取当前的帖子索引号?
{{ site.posts | size }} 是帖子的总数。 我需要的是 {{ site.posts.index }} 或 {{ page.index }}。
我正在尝试在每个帖子页面上显示一个计数器。示例:发布 43 of 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 }}
获取模板中的帖子索引【讨论】: