【问题标题】:How to retrieve the current post index number in Jekyll?如何在 Jekyll 中检索当前的帖子索引号?
【发布时间】:2014-09-27 09:06:33
【问题描述】:

有没有办法从 site.posts 获取当前的帖子索引号?

{{ site.posts | size }} 是帖子的总数。 我需要的是 {{ site.posts.index }}{{ page.index }}

我正在尝试在每个帖子页面上显示一个计数器。示例:发布 43 of 2654

【问题讨论】:

    标签: ruby jekyll liquid


    【解决方案1】:

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

    【讨论】:

    • 它可以工作,但是为每个帖子循环所有帖子以查找索引太昂贵了,不幸的是,这使得生成时间过长。还有什么想法吗?有什么方法可以以编程方式将索引号添加到前端?
    【解决方案2】:

    (回答我自己的问题,也许对其他人有帮助)

    确实有另一种方法(并且不会对性能造成重大影响)使用简单的 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 }}

    获取模板中的帖子索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-15
      • 2011-06-16
      • 1970-01-01
      • 2012-05-15
      • 2013-10-09
      • 2013-03-07
      • 2011-02-02
      • 1970-01-01
      相关资源
      最近更新 更多