@@ -1,32 +1,9 @@
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−
211--------------------------------------------------------------------------------
22−{-# LANGUAGE CPP #-}
232{-# LANGUAGE ExistentialQuantification #-}
24−{-# LANGUAGE RankNTypes #-}
253module Hakyll.Web.Template.Context
264 ( ContextField (..)
275 , Context (..)
286 , field
29− , boolField
307 , constField
318 , listField
329 , listFieldWith
@@ -39,49 +16,43 @@ module Hakyll.Web.Template.Context
3916 , urlField
4017 , pathField
4118 , titleField
42− , snippetField
4319 , dateField
4420 , dateFieldWith
4521 , getItemUTC
46− , getItemModificationTime
4722 , modificationTimeField
4823 , modificationTimeFieldWith
4924 , teaserField
50− , teaserFieldWithSeparator
5125 , missingField
52− , bindItem
5326 ) where
5427
5528
5629--------------------------------------------------------------------------------
57−import Control.Applicative (Alternative (..))
30+import Control.Applicative (Alternative (..), (<$>))
5831import Control.Monad (msum)
59−import Data.List (intercalate, tails)
60−#if MIN_VERSION_base(4,9,0)
61−import Data.Semigroup (Semigroup (..))
62−#endif
32+import Data.List (intercalate)
33+import qualified Data.Map as M
34+import Data.Monoid (Monoid (..))
6335import Data.Time.Clock (UTCTime (..))
64−import Data.Time.Format (formatTime)
65−import qualified Data.Time.Format as TF
66−import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
36+import Data.Time.Format (formatTime, parseTime)
37+import System.FilePath (takeBaseName, splitDirectories)
38+import System.Locale (TimeLocale, defaultTimeLocale)
39+
40+
41+--------------------------------------------------------------------------------
6742import Hakyll.Core.Compiler
6843import Hakyll.Core.Compiler.Internal
6944import Hakyll.Core.Identifier
7045import Hakyll.Core.Item
7146import Hakyll.Core.Metadata
7247import Hakyll.Core.Provider
73−import Hakyll.Core.Util.String (needlePrefix, splitAll)
48+import Hakyll.Core.Util.String (splitAll, needlePrefix)
7449import Hakyll.Web.Html
75−import Prelude hiding (id)
76−import System.FilePath (dropExtension, splitDirectories,
77− takeBaseName)
7850
7951
8052--------------------------------------------------------------------------------
8153-- | Mostly for internal usage
8254data ContextField
83− = EmptyField
84− | StringField String
55+ = StringField String
8556 | forall a. ListField (Context a) [Item a]
8657
8758
@@ -106,140 +77,61 @@ newtype Context a = Context
10677
10778
10879--------------------------------------------------------------------------------
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
11980instance Monoid (Context a) where
12081 mempty = missingField
12182 mappend (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
122−#endif
12383
12484
12585--------------------------------------------------------------------------------
12686field' :: String -> (Item a -> Compiler ContextField) -> Context a
127−field' key value = Context $ \k _ i ->
128− if k == key
129− then value i
130− else noResult $ "Tried field " ++ key
87+field' key value = Context $ \k _ i -> if k == key then value i else empty
13188
13289
13390--------------------------------------------------------------------------------
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'.
91+-- | Constructs a new field in the 'Context.'
14392field
14493 :: String -- ^ Key
14594 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
146− -- on the item (e.g. accessing metadata)
95+ -- on the item
14796 -> Context a
14897field key value = field' key (fmap StringField . value)
14998
15099
151100--------------------------------------------------------------------------------
152−-- | Creates a 'field' to use with the @$if()$@ template macro.
153−-- Attempting to substitute the field into the template will cause an error.
154−boolField
155− :: String
156− -> (Item a -> Bool)
157− -> Context a
158−boolField name f = field' name (\i -> if f i
159− then return EmptyField
160− else noResult $ "Field " ++ name ++ " is false")
161−
162−
163−--------------------------------------------------------------------------------
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
101+-- | Creates a 'field' that does not depend on the 'Item'
102+constField :: String -> String -> Context a
169103constField key = field key . const . return
170104
171105
172106--------------------------------------------------------------------------------
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.
176107listField :: String -> Context a -> Compiler [Item a] -> Context b
177108listField key c xs = listFieldWith key c (const xs)
178109
179110
180111--------------------------------------------------------------------------------
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.
187112listFieldWith
188113 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
189114listFieldWith key c f = field' key $ fmap (ListField c) . f
190115
191116
192117--------------------------------------------------------------------------------
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
118+functionField :: String -> ([String] -> Item a -> Compiler String) -> Context a
200119functionField name value = Context $ \k args i ->
201120 if k == name
202121 then StringField <$> value args i
203− else noResult $ "Tried function field " ++ name
122+ else empty
204123
205124
206125--------------------------------------------------------------------------------
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−--
216126mapContext :: (String -> String) -> Context a -> Context a
217127mapContext f (Context c) = Context $ \k a i -> do
218128 fld <- c k a i
219129 case fld of
220− EmptyField -> wrongType "boolField"
221130 StringField str -> return $ StringField (f str)
222− _ -> wrongType "ListField"
223− where
224− wrongType typ = fail $ "Hakyll.Web.Template.Context.mapContext: " ++
225− "can't map over a " ++ typ ++ "!"
131+ ListField _ _ -> fail $
132+ "Hakyll.Web.Template.Context.mapContext: " ++
133+ "can't map over a ListField!"
226134
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()'"
243135
244136--------------------------------------------------------------------------------
245137-- | A context that contains (in that order)
@@ -259,7 +151,8 @@ defaultContext =
259151 metadataField `mappend`
260152 urlField "url" `mappend`
261153 pathField "path" `mappend`
262− titleField "title"
154+ titleField "title" `mappend`
155+ missingField
263156
264157
265158--------------------------------------------------------------------------------
@@ -277,20 +170,15 @@ bodyField key = field key $ return . itemBody
277170-- | Map any field to its metadata value, if present
278171metadataField :: Context a
279172metadataField = Context $ \k _ i -> do
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
173+ value <- getMetadataField (itemIdentifier i) k
174+ maybe empty (return . StringField) value
285175
286176
287177--------------------------------------------------------------------------------
288178-- | Absolute url to the resulting item
289179urlField :: String -> Context a
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
180+urlField key = field key $
181+ fmap (maybe empty toUrl) . getRoute . itemIdentifier
294182
295183
296184--------------------------------------------------------------------------------
@@ -337,16 +225,10 @@ titleField = mapContext takeBaseName . pathField
337225-- Alternatively, when the metadata has a field called @path@ in a
338226-- @folder/yyyy-mm-dd-title.extension@ format (the convention for pages)
339227-- and no @published@ metadata field set, this function can render
340−-- the date. This pattern matches the file name or directory names
228+-- the date. This pattern matches the file name or directory names
341229-- that begins with @yyyy-mm-dd@ . For example:
342230-- @folder//yyyy-mm-dd-title//dist//main.extension@ .
343231-- 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.
350232
351233dateField :: String -- ^ Key in which the rendered date should be placed
352234 -> String -- ^ Format to use on the date
@@ -357,7 +239,7 @@ dateField = dateFieldWith defaultTimeLocale
357239--------------------------------------------------------------------------------
358240-- | This is an extended version of 'dateField' that allows you to
359241-- specify a time locale that is used for outputting the date. For more
360−-- details, see 'dateField' and 'formatTime'.
242+-- details, see 'dateField'.
361243dateFieldWith :: TimeLocale -- ^ Output time locale
362244 -> String -- ^ Destination key
363245 -> String -- ^ Format to use on the date
@@ -377,18 +259,17 @@ getItemUTC :: MonadMetadata m
377259 -> m UTCTime -- ^ Parsed UTCTime
378260getItemUTC locale id' = do
379261 metadata <- getMetadata id'
380− let tryField k fmt = lookupString k metadata >>= parseTime' fmt
381− paths = splitDirectories $ (dropExtension . toFilePath) id'
262+ let tryField k fmt = M.lookup k metadata >>= parseTime' fmt
263+ paths = splitDirectories $ toFilePath id'
382264
383265 maybe empty' return $ msum $
384266 [tryField "published" fmt | fmt <- formats] ++
385267 [tryField "date" fmt | fmt <- formats] ++
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]
268+ [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths]
388269 where
389270 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
390271 "could not parse time for " ++ show id'
391− parseTime' = parseTimeM True locale
272+ parseTime' = parseTime locale
392273 formats =
393274 [ "%a, %d %b %Y %H:%M:%S %Z"
394275 , "%Y-%m-%dT%H:%M:%S%Z"
@@ -401,33 +282,20 @@ getItemUTC locale id' = do
401282
402283
403284--------------------------------------------------------------------------------
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.
416285modificationTimeField :: String -- ^ Key
417286 -> String -- ^ Format
418− -> Context a -- ^ Resulting context
287+ -> Context a -- ^ Resuting context
419288modificationTimeField = modificationTimeFieldWith defaultTimeLocale
420289
421290
422291--------------------------------------------------------------------------------
423−-- | Creates a field with the last modification date of the underlying item
424−-- in a custom localisation format (see 'formatTime').
425292modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
426293 -> String -- ^ Key
427294 -> String -- ^ Format
428295 -> Context a -- ^ Resulting context
429296modificationTimeFieldWith locale key fmt = field key $ \i -> do
430− mtime <- getItemModificationTime $ itemIdentifier i
297+ provider <- compilerProvider <$> compilerAsk
298+ let mtime = resourceModificationTime provider $ itemIdentifier i
431299 return $ formatTime locale fmt mtime
432300
433301
@@ -438,21 +306,9 @@ modificationTimeFieldWith locale key fmt = field key $ \i -> do
438306teaserField :: String -- ^ Key to use
439307 -> Snapshot -- ^ Snapshot to load
440308 -> Context String -- ^ Resulting context
441−teaserField = teaserFieldWithSeparator teaserSeparator
442−
443−
444−--------------------------------------------------------------------------------
445−-- | A context with "teaser" key which contain a teaser of the item, defined as
446−-- the snapshot content before the teaser separator. The item is loaded from the
447−-- given snapshot (which should be saved in the user code before any templates
448−-- are applied).
449−teaserFieldWithSeparator :: String -- ^ Separator to use
450− -> String -- ^ Key to use
451− -> Snapshot -- ^ Snapshot to load
452− -> Context String -- ^ Resulting context
453−teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
309+teaserField key snapshot = field key $ \item -> do
454310 body <- itemBody <$> loadSnapshot (itemIdentifier item) snapshot
455− case needlePrefix separator body of
311+ case needlePrefix teaserSeparator body of
456312 Nothing -> fail $
457313 "Hakyll.Web.Template.Context: no teaser defined for " ++
458314 show (itemIdentifier item)
@@ -460,22 +316,7 @@ teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
460316
461317
462318--------------------------------------------------------------------------------
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.
465319missingField :: Context a
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
320+missingField = Context $ \k _ i -> fail $
321+ "Missing field $" ++ k ++ "$ in context for item " ++
322+ show (itemIdentifier i)