1

使用 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 ——当我尝试编译该站点时,我收到一条错误消息,指出“日期”方法未定义。

4

2 回答 2

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

谢谢!

于 2012-03-07T22:15:48.143 回答
0

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

你快到了。我相信您粘贴的代码正确地将文章划分为年/月。现在您需要显示它们。您可以使用 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 %>

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

于 2012-03-03T09:09:52.250 回答