@@ -1,5 +1,27 @@
1+-- | This module provides 'Context's which are used to expand expressions in
2+-- templates and allow for arbitrary customisation.
3+--
4+-- 'Template's define a small expression DSL which consists of strings,
5+-- identifiers and function application. There is no type system, every value is
6+-- a string and on the top level they get substituted verbatim into the page.
7+--
8+-- For example, you can build a context that contains
9+--
10+-- > … <> functionField "concat" (const . concat) <> …
11+--
12+-- which will allow you to use the @concat@ identifier as a function that takes
13+-- arbitrarily many stings and concatenates them to a new string:
14+--
15+-- > $partial(concat("templates/categories/", category))$
16+--
17+-- This will evaluate the @category@ field in the context, then prepend he path,
18+-- and include the referenced file as a template.
19+
20+
121--------------------------------------------------------------------------------
22+{-# LANGUAGE CPP #-}
223{-# LANGUAGE ExistentialQuantification #-}
24+{-# LANGUAGE RankNTypes #-}
325module Hakyll.Web.Template.Context
426 ( ContextField (..)
527 , Context (..)
@@ -17,30 +39,31 @@ module Hakyll.Web.Template.Context
1739 , urlField
1840 , pathField
1941 , titleField
42+ , snippetField
2043 , dateField
2144 , dateFieldWith
2245 , getItemUTC
46+ , getItemModificationTime
2347 , modificationTimeField
2448 , modificationTimeFieldWith
2549 , teaserField
2650 , teaserFieldWithSeparator
2751 , missingField
52+ , bindItem
2853 ) where
2954
3055
3156--------------------------------------------------------------------------------
32−import Control.Applicative (Alternative (..), pure, (<$>))
57+import Control.Applicative (Alternative (..))
3358import Control.Monad (msum)
34−import Data.List (intercalate)
35−import qualified Data.Map as M
36−import Data.Monoid (Monoid (..))
59+import Data.List (intercalate, tails)
60+#if MIN_VERSION_base(4,9,0)
61+import Data.Semigroup (Semigroup (..))
62+#endif
3763import Data.Time.Clock (UTCTime (..))
38−import Data.Time.Format (TimeLocale, defaultTimeLocale,
39− formatTime, parseTime)
40−import System.FilePath (splitDirectories, takeBaseName)
41−
42−
43−--------------------------------------------------------------------------------
64+import Data.Time.Format (formatTime)
65+import qualified Data.Time.Format as TF
66+import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
4467import Hakyll.Core.Compiler
4568import Hakyll.Core.Compiler.Internal
4669import Hakyll.Core.Identifier
@@ -49,12 +72,16 @@ import Hakyll.Core.Metadata
4972import Hakyll.Core.Provider
5073import Hakyll.Core.Util.String (needlePrefix, splitAll)
5174import Hakyll.Web.Html
75+import Prelude hiding (id)
76+import System.FilePath (dropExtension, splitDirectories,
77+ takeBaseName)
5278
5379
5480--------------------------------------------------------------------------------
5581-- | Mostly for internal usage
5682data ContextField
57− = StringField String
83+ = EmptyField
84+ | StringField String
5885 | forall a. ListField (Context a) [Item a]
5986
6087
@@ -79,72 +106,140 @@ newtype Context a = Context
79106
80107
81108--------------------------------------------------------------------------------
109+-- | Tries to find a key in the left context,
110+-- or when that fails in the right context.
111+#if MIN_VERSION_base(4,9,0)
112+instance Semigroup (Context a) where
113+ (<>) (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
114+
115+instance Monoid (Context a) where
116+ mempty = missingField
117+ mappend = (<>)
118+#else
82119instance Monoid (Context a) where
83120 mempty = missingField
84121 mappend (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
122+#endif
85123
86124
87125--------------------------------------------------------------------------------
88126field' :: String -> (Item a -> Compiler ContextField) -> Context a
89−field' key value = Context $ \k _ i -> if k == key then value i else empty
127+field' key value = Context $ \k _ i ->
128+ if k == key
129+ then value i
130+ else noResult $ "Tried field " ++ key
90131
91132
92133--------------------------------------------------------------------------------
93−-- | Constructs a new field in the 'Context.'
134+-- | Constructs a new field for a 'Context'.
135+-- If the key matches, the compiler is run and its result is substituted in the
136+-- template.
137+--
138+-- If the compiler fails, the field will be considered non-existent
139+-- in an @$if()$@ macro or ultimately break the template application
140+-- (unless the key is found in another context when using '<>').
141+-- Use 'empty' or 'noResult' for intentional failures of fields used in
142+-- @$if()$@, to distinguish them from exceptions thrown with 'fail'.
94143field
95144 :: String -- ^ Key
96145 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
97− -- on the item
146+ -- on the item (e.g. accessing metadata)
98147 -> Context a
99148field key value = field' key (fmap StringField . value)
100149
101150
102151--------------------------------------------------------------------------------
103152-- | Creates a 'field' to use with the @$if()$@ template macro.
153+-- Attempting to substitute the field into the template will cause an error.
104154boolField
105155 :: String
106156 -> (Item a -> Bool)
107157 -> Context a
108−boolField name f = field name (\i -> if f i
109− then pure (error $ unwords ["no string value for bool field:",name])
110− else empty)
158+boolField name f = field' name (\i -> if f i
159+ then return EmptyField
160+ else noResult $ "Field " ++ name ++ " is false")
111161
112162
113163--------------------------------------------------------------------------------
114−-- | Creates a 'field' that does not depend on the 'Item'
115−constField :: String -> String -> Context a
164+-- | Creates a 'field' that does not depend on the 'Item' but always yields
165+-- the same string
166+constField :: String -- ^ Key
167+ -> String -- ^ Value
168+ -> Context a
116169constField key = field key . const . return
117170
118171
119172--------------------------------------------------------------------------------
173+-- | Creates a list field to be consumed by a @$for(…)$@ expression.
174+-- The compiler returns multiple items which are rendered in the loop body
175+-- with the supplied context.
120176listField :: String -> Context a -> Compiler [Item a] -> Context b
121177listField key c xs = listFieldWith key c (const xs)
122178
123179
124180--------------------------------------------------------------------------------
181+-- | Produces a new 'Context' which has list field 'key'. All fields from
182+-- 'c' are also accessible from the produced context.
183+-- Be careful when doing @listFieldWith k ca f <> cb@ as any fields in @ca@
184+-- will override fields in @cb@ with the same name.
185+-- Creates a list field like 'listField', but supplies the current page
186+-- to the compiler.
125187listFieldWith
126188 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
127189listFieldWith key c f = field' key $ fmap (ListField c) . f
128190
129191
130192--------------------------------------------------------------------------------
131−functionField :: String -> ([String] -> Item a -> Compiler String) -> Context a
193+-- | Creates a variadic function field.
194+--
195+-- The function will be called with the dynamically evaluated string arguments
196+-- from the template as well as the page that is currently rendered.
197+functionField :: String -- ^ Key
198+ -> ([String] -> Item a -> Compiler String) -- ^ Function
199+ -> Context a
132200functionField name value = Context $ \k args i ->
133201 if k == name
134202 then StringField <$> value args i
135− else empty
203+ else noResult $ "Tried function field " ++ name
136204
137205
138206--------------------------------------------------------------------------------
207+-- | Transform the respective string results of all fields in a context.
208+-- For example,
209+--
210+-- > mapContext (++"c") (constField "x" "a" <> constField "y" "b")
211+--
212+-- is equivalent to
213+--
214+-- > constField "x" "ac" <> constField "y" "bc"
215+--
139216mapContext :: (String -> String) -> Context a -> Context a
140217mapContext f (Context c) = Context $ \k a i -> do
141218 fld <- c k a i
142219 case fld of
220+ EmptyField -> wrongType "boolField"
143221 StringField str -> return $ StringField (f str)
144− ListField _ _ -> fail $
145− "Hakyll.Web.Template.Context.mapContext: " ++
146− "can't map over a ListField!"
222+ _ -> wrongType "ListField"
223+ where
224+ wrongType typ = fail $ "Hakyll.Web.Template.Context.mapContext: " ++
225+ "can't map over a " ++ typ ++ "!"
147226
227+--------------------------------------------------------------------------------
228+-- | A context that allows snippet inclusion. In processed file, use as:
229+--
230+-- > ...
231+-- > $snippet("path/to/snippet/")$
232+-- > ...
233+--
234+-- The contents of the included file will not be interpolated like @partial@
235+-- does it.
236+--
237+snippetField :: Context String
238+snippetField = functionField "snippet" f
239+ where
240+ f [contentsPath] _ = loadBody (fromFilePath contentsPath)
241+ f [] _ = fail "No argument to function 'snippet()'"
242+ f _ _ = fail "Too many arguments to function 'snippet()'"
148243
149244--------------------------------------------------------------------------------
150245-- | A context that contains (in that order)
@@ -164,8 +259,7 @@ defaultContext =
164259 metadataField `mappend`
165260 urlField "url" `mappend`
166261 pathField "path" `mappend`
167− titleField "title" `mappend`
168− missingField
262+ titleField "title"
169263
170264
171265--------------------------------------------------------------------------------
@@ -183,15 +277,20 @@ bodyField key = field key $ return . itemBody
183277-- | Map any field to its metadata value, if present
184278metadataField :: Context a
185279metadataField = Context $ \k _ i -> do
186− value <- getMetadataField (itemIdentifier i) k
187− maybe empty (return . StringField) value
280+ let id = itemIdentifier i
281+ empty' = noResult $ "No '" ++ k ++ "' field in metadata " ++
282+ "of item " ++ show id
283+ value <- getMetadataField id k
284+ maybe empty' (return . StringField) value
188285
189286
190287--------------------------------------------------------------------------------
191288-- | Absolute url to the resulting item
192289urlField :: String -> Context a
193−urlField key = field key $
194− fmap (maybe empty toUrl) . getRoute . itemIdentifier
290+urlField key = field key $ \i -> do
291+ let id = itemIdentifier i
292+ empty' = fail $ "No route url found for item " ++ show id
293+ fmap (maybe empty' toUrl) $ getRoute id
195294
196295
197296--------------------------------------------------------------------------------
@@ -242,6 +341,12 @@ titleField = mapContext takeBaseName . pathField
242341-- that begins with @yyyy-mm-dd@ . For example:
243342-- @folder//yyyy-mm-dd-title//dist//main.extension@ .
244343-- In case of multiple matches, the rightmost one is used.
344+--
345+-- As another alternative, if none of the above matches, and the file has a
346+-- path which contains nested directories specifying a date, then that date
347+-- will be used. In other words, if the path is of the form
348+-- @**//yyyy//mm//dd//**//main.extension@ .
349+-- As above, in case of multiple matches, the rightmost one is used.
245350
246351dateField :: String -- ^ Key in which the rendered date should be placed
247352 -> String -- ^ Format to use on the date
@@ -252,7 +357,7 @@ dateField = dateFieldWith defaultTimeLocale
252357--------------------------------------------------------------------------------
253358-- | This is an extended version of 'dateField' that allows you to
254359-- specify a time locale that is used for outputting the date. For more
255−-- details, see 'dateField'.
360+-- details, see 'dateField' and 'formatTime'.
256361dateFieldWith :: TimeLocale -- ^ Output time locale
257362 -> String -- ^ Destination key
258363 -> String -- ^ Format to use on the date
@@ -272,17 +377,18 @@ getItemUTC :: MonadMetadata m
272377 -> m UTCTime -- ^ Parsed UTCTime
273378getItemUTC locale id' = do
274379 metadata <- getMetadata id'
275− let tryField k fmt = M.lookup k metadata >>= parseTime' fmt
276− paths = splitDirectories $ toFilePath id'
380+ let tryField k fmt = lookupString k metadata >>= parseTime' fmt
381+ paths = splitDirectories $ (dropExtension . toFilePath) id'
277382
278383 maybe empty' return $ msum $
279384 [tryField "published" fmt | fmt <- formats] ++
280385 [tryField "date" fmt | fmt <- formats] ++
281− [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths]
386+ [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths] ++
387+ [parseTime' "%Y-%m-%d" $ intercalate "-" $ fnCand | fnCand <- map (take 3) $ reverse . tails $ paths]
282388 where
283389 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
284390 "could not parse time for " ++ show id'
285− parseTime' = parseTime locale
391+ parseTime' = parseTimeM True locale
286392 formats =
287393 [ "%a, %d %b %Y %H:%M:%S %Z"
288394 , "%Y-%m-%dT%H:%M:%S%Z"
@@ -295,20 +401,33 @@ getItemUTC locale id' = do
295401
296402
297403--------------------------------------------------------------------------------
404+-- | Get the time on which the actual file was last modified. This only works if
405+-- there actually is an underlying file, of couse.
406+getItemModificationTime
407+ :: Identifier
408+ -> Compiler UTCTime
409+getItemModificationTime identifier = do
410+ provider <- compilerProvider <$> compilerAsk
411+ return $ resourceModificationTime provider identifier
412+
413+
414+--------------------------------------------------------------------------------
415+-- | Creates a field with the last modification date of the underlying item.
298416modificationTimeField :: String -- ^ Key
299417 -> String -- ^ Format
300− -> Context a -- ^ Resuting context
418+ -> Context a -- ^ Resulting context
301419modificationTimeField = modificationTimeFieldWith defaultTimeLocale
302420
303421
304422--------------------------------------------------------------------------------
423+-- | Creates a field with the last modification date of the underlying item
424+-- in a custom localisation format (see 'formatTime').
305425modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
306426 -> String -- ^ Key
307427 -> String -- ^ Format
308428 -> Context a -- ^ Resulting context
309429modificationTimeFieldWith locale key fmt = field key $ \i -> do
310− provider <- compilerProvider <$> compilerAsk
311− let mtime = resourceModificationTime provider $ itemIdentifier i
430+ mtime <- getItemModificationTime $ itemIdentifier i
312431 return $ formatTime locale fmt mtime
313432
314433
@@ -341,7 +460,22 @@ teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
341460
342461
343462--------------------------------------------------------------------------------
463+-- | Constantly reports any field as missing. Mostly for internal usage,
464+-- it is the last choice in every context used in a template application.
344465missingField :: Context a
345−missingField = Context $ \k _ i -> fail $
346− "Missing field $" ++ k ++ "$ in context for item " ++
347− show (itemIdentifier i)
466+missingField = Context $ \k _ _ -> noResult $
467+ "Missing field '" ++ k ++ "' in context"
468+
469+parseTimeM :: Bool -> TimeLocale -> String -> String -> Maybe UTCTime
470+#if MIN_VERSION_time(1,5,0)
471+parseTimeM = TF.parseTimeM
472+#else
473+parseTimeM _ = TF.parseTime
474+#endif
475+
476+--------------------------------------------------------------------------------
477+
478+-- | Binds an 'Item' to a given 'Context', allowing it to be combined with any
479+-- other 'Context' of any type.
480+bindItem :: Context a -> Item a -> forall b. Context b
481+bindItem (Context ctx) ia = Context $ \k args _ -> ctx k args ia