Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatDateFieldValue for arbitrarily formatting date metadata #707

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions lib/Hakyll/Web/Template/Context.hs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ module Hakyll.Web.Template.Context
, snippetField
, dateField
, dateFieldWith
, formatDateFieldValue
, getItemUTC
, getItemModificationTime
, modificationTimeField
Expand Down Expand Up @@ -294,6 +295,29 @@ dateFieldWith locale key format = field key $ \i -> do
time <- getItemUTC locale $ itemIdentifier i
return $ formatTime locale format time

-- | Replace metadata date format with a new formatted date or do nothing
formatDateFieldValue :: String -- ^ Field name
-> String -- ^ Current format string
-> String -- ^ New format string
-> Context a -- ^ Resulting context
formatDateFieldValue name currFmt newFmt = Context $ \k _ i ->
if k == name
then (do value <- getMetadataField (itemIdentifier i) k
maybe empty (\v -> do
let mSDate = parseAndFormat newFmt v
case mSDate of
(Just sDate) -> (return . StringField) sDate
Nothing -> empty
) value
)
else empty
where
parseAndFormat :: String -> String -> Maybe String
parseAndFormat fmt' v' = do
let timeV = parseTimeM True defaultTimeLocale currFmt v' :: Maybe UTCTime
case timeV of
(Just t) -> Just $ formatTime defaultTimeLocale fmt' t
Nothing -> Nothing

--------------------------------------------------------------------------------
-- | Parser to try to extract and parse the time from the @published@
Expand Down
6 changes: 6 additions & 0 deletions tests/Hakyll/Web/Template/Context/Tests.hs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ testDateField = do
"posts/2019/05/10/tomorrow.md" "date" $
dateField "date" "%B %e, %Y"
date4 @=? "May 10, 2019"

date5 <- testContextDone store provider
"posts/2018-09-28-fall-prep.md" "modified" $
formatDateFieldValue "modified" "%Y-%m-%d %H:%M:%S" "%B %e, %Y - %r"
date5 @=? "September 29, 2018 - 06:58:15 PM"

cleanTestEnv


Expand Down
4 changes: 4 additions & 0 deletions tests/data/posts/2018-09-28-fall-prep.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
modified: 2018-09-29 18:58:15
---
Getting ready for fall season