是否可以使用Jekyll生成顶级index.html?

时间:2014-07-30 03:11:19

标签: ruby jekyll

我尝试使用Jekyll创建静态网站,并从Blogger导入内容。我想要做的其中一件事是拥有月度档案,我已经能够使用sample code I found成功生成:

module Jekyll

  class ArchiveGenerator < Generator
    safe true
    def generate(site)
      if site.layouts.key? 'archive_index'
        site.posts.group_by{ |c| {"month" => c.date.month, "year" => c.date.year} }.each do |period, posts|
          posts = posts.sort_by { |p| -p.date.to_f }
          archive_dir = File.join(period["year"].to_s(), "%02d" % period["month"].to_s())
          paginate(site, archive_dir, posts)
        end
        site.posts.group_by{ |c| {"year" => c.date.year} }.each do |period, posts|
          posts = posts.sort_by { |p| -p.date.to_f }
          archive_dir = period["year"].to_s()
          paginate(site, archive_dir, posts)
        end
      end
    end

    def paginate(site, dir, posts)
      pages = Pager.calculate_pages(posts, site.config['paginate'].to_i)
      (1..pages).each do |num_page|
        pager = Pager.new(site, num_page, posts, pages)
        archive_path = "/" + dir
        path = archive_path
        if num_page > 1
          path += "/page/#{num_page}"
        end
        newpage = ArchiveIndex.new(site, site.source, path, archive_path, posts)
        newpage.pager = pager
        site.pages << newpage

      end
    end
  end

  class ArchiveIndex < Page
    def initialize(site, base, dir, base_path, posts)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'

      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'archive_index.html')
      self.data['base'] = base_path
    end
  end
end

我希望顶级index.html文件是最近一个月有月份的月份档案。但是,我已尝试了各种方法将顶级目录指定为生成文件的目标,但未成功。这在Jekyll有可能吗?

1 个答案:

答案 0 :(得分:0)

你甚至不需要用Ruby 编写的插件(你在问题中发布的代码是)来显示头版最近一个月的帖子。

在Liquid中执行此操作非常容易,这意味着它可以在GitHub页面上工作(问题中的代码不会,because it's a plugin

<ul>
{% for post in site.posts %}
    {% assign currentmonth = post.date | date: "%B %Y" %}
    {% if prevmonth == null or currentmonth == prevmonth %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
    {% else %}
        {% break %}
    {% endif %}
    {% assign prevmonth = currentmonth %}
{% endfor %}
</ul>

简短说明:

  • 我们正在循环发布帖子,从每个日期获取月份和年份 post.date | date: "%B %Y"将返回类似“2014年7月”的内容)
  • 当前帖子的月份/年份等于上一篇文章的月份/年份时,将显示帖子
  • 上一篇文章的月/年将在开头(prevmonth == null)为空,因此我们将始终显示第一篇文章
  • 当我们到达上个月的第一篇文章时,我们将退出循环(使用{% break %} - 请注意{% break %} wasn't supported in earlier Liquid versions

加成:

如果你可以在一个页面上使用所有月份的月度档案,那么也可以在没有插件的情况下生成with a similar approach

相关问题