【问题标题】:Using nanoc to create a list of blog articles, sorted by month and year使用 nanoc 创建博客文章列表,按月和年排序
【发布时间】:2012-03-02 18:59:19
【问题描述】:

使用 nanoc 创建博客存档页面,我想显示一个类似于 http://daringfireball.net/archive/ 显示的列表

根据 nanoc 中博客文章的过时方式,我遇到了问题。这是我尝试过的代码:

by_yearmonth = @site.sorted_articles.group_by{ |a| [a.date.year,a.date.month] }
by_yearmonth.keys.sort.each do |yearmonth|
    articles_this_month = by_yearmonth[yearmonth]
    # code here to display month and year
    articles_this_month.each do |article|
        # code here to display title of blog post
    end
end

nanoc 似乎不理解 a.date.year 或 a.date.month -- 当我尝试编译该站点时,我收到一条错误消息,指出“日期”方法未定义。

【问题讨论】:

    标签: ruby blogs nanoc


    【解决方案1】:

    更新:由于 ddfreyne 的一些关键方向,这是最终工作的代码:

    # In lib/helpers/blogging.rb:
    def grouped_articles
      sorted_articles.group_by do |a|
        [ Time.parse(a[:created_at]).year, Time.parse(a[:created_at]).month ]
      end.sort.reverse
    end
    
    # In blog archive item:
    <% grouped_articles.each do |yearmonth, articles_this_month| %>
        <h2>Year <%= yearmonth.first %>, month <%= yearmonth.last %></h2>
        <% articles_this_month.each do |article| %>
            <h3><%= article[:title] %></h3>
        <% end %>
    <% end %>
    

    谢谢!

    【讨论】:

      【解决方案2】:

      您的问题缺少一个问题。 :)

      你快到了。我相信您粘贴的代码正确地将文章划分为年/月。现在您需要显示它们。您可以使用 ERB 或 Haml 来做到这一点(有些人更喜欢前者,其他人更喜欢后者)。例如,使用 ERB:

      # somewhere in lib/ (I propose lib/helpers/blogging.rb)
      require 'date'
      def grouped_articles
        sorted_articles.group_by do |a|
          [ Date.parse(a[:date].year, Date.parse(a[:date]).month ]
        end.sort
      end
      
      # in your blog archive item
      <% grouped_articles.each_pair do |yearmonth, articles_this_month| %>
          <h1>Year <%= yearmonth.first %>, month <%= yearmonth.last %></h1>
          <% articles_this_month.each do |article| %>
              <h2><%= article[:title] %></h2>
          <% end %>
      <% end %>
      

      我没有测试过,不过这就是它的要点。

      【讨论】:

      • 非常感谢您的回复(以及制作和支持如此酷的网络创作工具!)。我应该澄清一下,我确实了解如何显示结果,为了简洁起见,我只是将它们排除在上述代码之外。我对上述任何一个示例中的代码的问题是,我不能让它首先给我结果!当我尝试编译时,我收到错误“NoMethodError: undefined method `date' for #<:item:0x10fab3b40>”。所以我认为 nanoc 一定想要一种不同的解析日期的方法,但我不知道那会是什么。再次感谢!
      • 啊,我的错。 a.date 不起作用;要访问您需要 [:date] 的属性。由于它是一个字符串,因此应使用 Date.parse。我已经更新了我的代码 sn-p。
      猜你喜欢
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 2020-08-25
      • 2021-06-18
      相关资源
      最近更新 更多