@@ -1,27 +1,6 @@
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--------------------------------------------------------------------------------
222{-# LANGUAGE CPP #-}
233{-# LANGUAGE ExistentialQuantification #-}
24−{-# LANGUAGE RankNTypes #-}
254module Hakyll.Web.Template.Context
265 ( ContextField (..)
276 , Context (..)
@@ -39,31 +18,30 @@ module Hakyll.Web.Template.Context
3918 , urlField
4019 , pathField
4120 , titleField
42− , snippetField
4321 , dateField
4422 , dateFieldWith
4523 , getItemUTC
46− , getItemModificationTime
4724 , modificationTimeField
4825 , modificationTimeFieldWith
4926 , teaserField
5027 , teaserFieldWithSeparator
5128 , missingField
52− , bindItem
5329 ) where
5430
5531
5632--------------------------------------------------------------------------------
57−import Control.Applicative (Alternative (..))
33+import Control.Applicative (Alternative (..), pure, (<$>))
5834import Control.Monad (msum)
59−import Data.List (intercalate, tails)
60−#if MIN_VERSION_base(4,9,0)
61−import Data.Semigroup (Semigroup (..))
62−#endif
35+import Data.List (intercalate)
36+import qualified Data.Map as M
37+import Data.Monoid (Monoid (..))
6338import Data.Time.Clock (UTCTime (..))
6439import Data.Time.Format (formatTime)
6540import qualified Data.Time.Format as TF
6641import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
42+import System.FilePath (splitDirectories, takeBaseName)
43+
44+--------------------------------------------------------------------------------
6745import Hakyll.Core.Compiler
6846import Hakyll.Core.Compiler.Internal
6947import Hakyll.Core.Identifier
@@ -72,16 +50,12 @@ import Hakyll.Core.Metadata
7250import Hakyll.Core.Provider
7351import Hakyll.Core.Util.String (needlePrefix, splitAll)
7452import Hakyll.Web.Html
75−import Prelude hiding (id)
76−import System.FilePath (dropExtension, splitDirectories,
77− takeBaseName)
7853
7954
8055--------------------------------------------------------------------------------
8156-- | Mostly for internal usage
8257data ContextField
83− = EmptyField
84− | StringField String
58+ = StringField String
8559 | forall a. ListField (Context a) [Item a]
8660
8761
@@ -106,140 +80,72 @@ newtype Context a = Context
10680
10781
10882--------------------------------------------------------------------------------
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
11983instance Monoid (Context a) where
12084 mempty = missingField
12185 mappend (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
122−#endif
12386
12487
12588--------------------------------------------------------------------------------
12689field' :: 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
90+field' key value = Context $ \k _ i -> if k == key then value i else empty
13191
13292
13393--------------------------------------------------------------------------------
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'.
94+-- | Constructs a new field in the 'Context.'
14395field
14496 :: String -- ^ Key
14597 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
146− -- on the item (e.g. accessing metadata)
98+ -- on the item
14799 -> Context a
148100field key value = field' key (fmap StringField . value)
149101
150102
151103--------------------------------------------------------------------------------
152104-- | Creates a 'field' to use with the @$if()$@ template macro.
153−-- Attempting to substitute the field into the template will cause an error.
154105boolField
155106 :: String
156107 -> (Item a -> Bool)
157108 -> Context a
158−boolField name f = field' name (\i -> if f i
159− then return EmptyField
160− else noResult $ "Field " ++ name ++ " is false")
109+boolField name f = field name (\i -> if f i
110+ then pure (error $ unwords ["no string value for bool field:",name])
111+ else empty)
161112
162113
163114--------------------------------------------------------------------------------
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
115+-- | Creates a 'field' that does not depend on the 'Item'
116+constField :: String -> String -> Context a
169117constField key = field key . const . return
170118
171119
172120--------------------------------------------------------------------------------
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.
176121listField :: String -> Context a -> Compiler [Item a] -> Context b
177122listField key c xs = listFieldWith key c (const xs)
178123
179124
180125--------------------------------------------------------------------------------
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.
187126listFieldWith
188127 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
189128listFieldWith key c f = field' key $ fmap (ListField c) . f
190129
191130
192131--------------------------------------------------------------------------------
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
132+functionField :: String -> ([String] -> Item a -> Compiler String) -> Context a
200133functionField name value = Context $ \k args i ->
201134 if k == name
202135 then StringField <$> value args i
203− else noResult $ "Tried function field " ++ name
136+ else empty
204137
205138
206139--------------------------------------------------------------------------------
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−--
216140mapContext :: (String -> String) -> Context a -> Context a
217141mapContext f (Context c) = Context $ \k a i -> do
218142 fld <- c k a i
219143 case fld of
220− EmptyField -> wrongType "boolField"
221144 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 ++ "!"
145+ ListField _ _ -> fail $
146+ "Hakyll.Web.Template.Context.mapContext: " ++
147+ "can't map over a ListField!"
226148
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()'"
243149
244150--------------------------------------------------------------------------------
245151-- | A context that contains (in that order)
@@ -259,7 +165,8 @@ defaultContext =
259165 metadataField `mappend`
260166 urlField "url" `mappend`
261167 pathField "path" `mappend`
262− titleField "title"
168+ titleField "title" `mappend`
169+ missingField
263170
264171
265172--------------------------------------------------------------------------------
@@ -277,20 +184,15 @@ bodyField key = field key $ return . itemBody
277184-- | Map any field to its metadata value, if present
278185metadataField :: Context a
279186metadataField = 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
187+ value <- getMetadataField (itemIdentifier i) k
188+ maybe empty (return . StringField) value
285189
286190
287191--------------------------------------------------------------------------------
288192-- | Absolute url to the resulting item
289193urlField :: 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
194+urlField key = field key $
195+ fmap (maybe empty toUrl) . getRoute . itemIdentifier
294196
295197
296198--------------------------------------------------------------------------------
@@ -341,12 +243,6 @@ titleField = mapContext takeBaseName . pathField
341243-- that begins with @yyyy-mm-dd@ . For example:
342244-- @folder//yyyy-mm-dd-title//dist//main.extension@ .
343245-- 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.
350246
351247dateField :: String -- ^ Key in which the rendered date should be placed
352248 -> String -- ^ Format to use on the date
@@ -357,7 +253,7 @@ dateField = dateFieldWith defaultTimeLocale
357253--------------------------------------------------------------------------------
358254-- | This is an extended version of 'dateField' that allows you to
359255-- specify a time locale that is used for outputting the date. For more
360−-- details, see 'dateField' and 'formatTime'.
256+-- details, see 'dateField'.
361257dateFieldWith :: TimeLocale -- ^ Output time locale
362258 -> String -- ^ Destination key
363259 -> String -- ^ Format to use on the date
@@ -377,14 +273,13 @@ getItemUTC :: MonadMetadata m
377273 -> m UTCTime -- ^ Parsed UTCTime
378274getItemUTC locale id' = do
379275 metadata <- getMetadata id'
380− let tryField k fmt = lookupString k metadata >>= parseTime' fmt
381− paths = splitDirectories $ (dropExtension . toFilePath) id'
276+ let tryField k fmt = M.lookup k metadata >>= parseTime' fmt
277+ paths = splitDirectories $ toFilePath id'
382278
383279 maybe empty' return $ msum $
384280 [tryField "published" fmt | fmt <- formats] ++
385281 [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]
282+ [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths]
388283 where
389284 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
390285 "could not parse time for " ++ show id'
@@ -401,33 +296,20 @@ getItemUTC locale id' = do
401296
402297
403298--------------------------------------------------------------------------------
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.
416299modificationTimeField :: String -- ^ Key
417300 -> String -- ^ Format
418− -> Context a -- ^ Resulting context
301+ -> Context a -- ^ Resuting context
419302modificationTimeField = modificationTimeFieldWith defaultTimeLocale
420303
421304
422305--------------------------------------------------------------------------------
423−-- | Creates a field with the last modification date of the underlying item
424−-- in a custom localisation format (see 'formatTime').
425306modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
426307 -> String -- ^ Key
427308 -> String -- ^ Format
428309 -> Context a -- ^ Resulting context
429310modificationTimeFieldWith locale key fmt = field key $ \i -> do
430− mtime <- getItemModificationTime $ itemIdentifier i
311+ provider <- compilerProvider <$> compilerAsk
312+ let mtime = resourceModificationTime provider $ itemIdentifier i
431313 return $ formatTime locale fmt mtime
432314
433315
@@ -460,11 +342,10 @@ teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
460342
461343
462344--------------------------------------------------------------------------------
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.
465345missingField :: Context a
466−missingField = Context $ \k _ _ -> noResult $
467− "Missing field '" ++ k ++ "' in context"
346+missingField = Context $ \k _ i -> fail $
347+ "Missing field $" ++ k ++ "$ in context for item " ++
348+ show (itemIdentifier i)
468349
469350parseTimeM :: Bool -> TimeLocale -> String -> String -> Maybe UTCTime
470351#if MIN_VERSION_time(1,5,0)
@@ -472,10 +353,3 @@ parseTimeM = TF.parseTimeM
472353#else
473354parseTimeM _ = TF.parseTime
474355#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