2

我想在我的帖子中添加一个名为 的自定义字段coolness,如下所示:

---
title: Something
coolness: 10
---

然后我想按酷度对我的帖子进行排序。我怎么做?我知道我可以按日期排序: posts <- recentFirst =<< loadAll "posts/*" 使用recentFirst,但这是内置的,我真的不知道如何修改它来排序,coolness因为它使用一些自定义方法来找出帖子的日期。

4

1 回答 1

1

我们想使用MonadMetadataand getMetadataFieldfrom Hakyll来读取coolness,然后将其解析为一个数字,并按该数字排序。

从源代码中recentFirst大量窃取,您可以编写如下内容:

{-# LANGUAGE TupleSections #-}
import Hakyll
import Control.Monad (void, (>>=), liftM)
import Data.Ord (comparing)
import Data.List(sortOn, sortBy)
import Data.Maybe(fromMaybe)
import Text.Read(readMaybe)
import Data.Foldable (toList)

-- this parses the coolness out of an item
-- it defaults to 0 if it's missing, or can't be parsed as an Int
coolness :: MonadMetadata m => Item a -> m Int
coolness i = do 
    mStr <- getMetadataField (itemIdentifier i) "coolness"
    return $ (fromMaybe 0 $ mStr >>= readMaybe)

byCoolness :: MonadMetadata m => [Item a] -> m [Item a]
byCoolness = sortByM coolness
  where
    sortByM :: (Monad m, Ord k) => (a -> m k) -> [a] -> m [a]
    sortByM f xs = liftM (map fst . sortBy (comparing snd)) $
                   mapM (\x -> liftM (x,) (f x)) xs

这对提取的酷度值进行排序。它会增加酷度,所以如果你想要“最酷的优先”,请执行以下操作:

posts <- reverse <$> (byCoolness =<< loadAll "posts/*")
于 2020-07-03T13:27:36.953 回答