@@ -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 (..)
@@ -49,17 +28,13 @@ module Hakyll.Web.Template.Context
4928 , teaserField
5029 , teaserFieldWithSeparator
5130 , missingField
52− , bindItem
5331 ) where
5432
5533
5634--------------------------------------------------------------------------------
5735import Control.Applicative (Alternative (..))
5836import Control.Monad (msum)
59−import Data.List (intercalate, tails)
60−#if MIN_VERSION_base(4,9,0)
61−import Data.Semigroup (Semigroup (..))
62−#endif
37+import Data.List (intercalate)
6338import Data.Time.Clock (UTCTime (..))
6439import Data.Time.Format (formatTime)
6540import qualified Data.Time.Format as TF
@@ -72,16 +47,13 @@ import Hakyll.Core.Metadata
7247import Hakyll.Core.Provider
7348import Hakyll.Core.Util.String (needlePrefix, splitAll)
7449import Hakyll.Web.Html
75−import Prelude hiding (id)
76−import System.FilePath (dropExtension, splitDirectories,
77− takeBaseName)
50+import System.FilePath (splitDirectories, takeBaseName)
7851
7952
8053--------------------------------------------------------------------------------
8154-- | Mostly for internal usage
8255data ContextField
83− = EmptyField
84− | StringField String
56+ = StringField String
8557 | forall a. ListField (Context a) [Item a]
8658
8759
@@ -106,123 +78,71 @@ newtype Context a = Context
10678
10779
10880--------------------------------------------------------------------------------
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
11981instance Monoid (Context a) where
12082 mempty = missingField
12183 mappend (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
122−#endif
12384
12485
12586--------------------------------------------------------------------------------
12687field' :: 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
88+field' key value = Context $ \k _ i -> if k == key then value i else empty
13189
13290
13391--------------------------------------------------------------------------------
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'.
92+-- | Constructs a new field in the 'Context.'
14393field
14494 :: String -- ^ Key
14595 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
146− -- on the item (e.g. accessing metadata)
96+ -- on the item
14797 -> Context a
14898field key value = field' key (fmap StringField . value)
14999
150100
151101--------------------------------------------------------------------------------
152102-- | Creates a 'field' to use with the @$if()$@ template macro.
153−-- Attempting to substitute the field into the template will cause an error.
154103boolField
155104 :: String
156105 -> (Item a -> Bool)
157106 -> Context a
158−boolField name f = field' name (\i -> if f i
159− then return EmptyField
160− else noResult $ "Field " ++ name ++ " is false")
107+boolField name f = field name (\i -> if f i
108+ then pure (error $ unwords ["no string value for bool field:",name])
109+ else empty)
161110
162111
163112--------------------------------------------------------------------------------
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
113+-- | Creates a 'field' that does not depend on the 'Item'
114+constField :: String -> String -> Context a
169115constField key = field key . const . return
170116
171117
172118--------------------------------------------------------------------------------
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.
176119listField :: String -> Context a -> Compiler [Item a] -> Context b
177120listField key c xs = listFieldWith key c (const xs)
178121
179122
180123--------------------------------------------------------------------------------
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.
187124listFieldWith
188125 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
189126listFieldWith key c f = field' key $ fmap (ListField c) . f
190127
191128
192129--------------------------------------------------------------------------------
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
130+functionField :: String -> ([String] -> Item a -> Compiler String) -> Context a
200131functionField name value = Context $ \k args i ->
201132 if k == name
202133 then StringField <$> value args i
203− else noResult $ "Tried function field " ++ name
134+ else empty
204135
205136
206137--------------------------------------------------------------------------------
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−--
216138mapContext :: (String -> String) -> Context a -> Context a
217139mapContext f (Context c) = Context $ \k a i -> do
218140 fld <- c k a i
219141 case fld of
220− EmptyField -> wrongType "boolField"
221142 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 ++ "!"
143+ ListField _ _ -> fail $
144+ "Hakyll.Web.Template.Context.mapContext: " ++
145+ "can't map over a ListField!"
226146
227147--------------------------------------------------------------------------------
228148-- | A context that allows snippet inclusion. In processed file, use as:
@@ -231,15 +151,15 @@ mapContext f (Context c) = Context $ \k a i -> do
231151-- > $snippet("path/to/snippet/")$
232152-- > ...
233153--
234−-- The contents of the included file will not be interpolated like @partial@
235−-- does it.
154+-- The contents of the included file will not be interpolated.
236155--
237156snippetField :: Context String
238157snippetField = functionField "snippet" f
239158 where
240159 f [contentsPath] _ = loadBody (fromFilePath contentsPath)
241− f [] _ = fail "No argument to function 'snippet()'"
242− f _ _ = fail "Too many arguments to function 'snippet()'"
160+ f _ i = error $
161+ "Too many arguments to function 'snippet()' in item " ++
162+ show (itemIdentifier i)
243163
244164--------------------------------------------------------------------------------
245165-- | A context that contains (in that order)
@@ -259,7 +179,8 @@ defaultContext =
259179 metadataField `mappend`
260180 urlField "url" `mappend`
261181 pathField "path" `mappend`
262− titleField "title"
182+ titleField "title" `mappend`
183+ missingField
263184
264185
265186--------------------------------------------------------------------------------
@@ -277,20 +198,15 @@ bodyField key = field key $ return . itemBody
277198-- | Map any field to its metadata value, if present
278199metadataField :: Context a
279200metadataField = 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
201+ value <- getMetadataField (itemIdentifier i) k
202+ maybe empty (return . StringField) value
285203
286204
287205--------------------------------------------------------------------------------
288206-- | Absolute url to the resulting item
289207urlField :: 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
208+urlField key = field key $
209+ fmap (maybe empty toUrl) . getRoute . itemIdentifier
294210
295211
296212--------------------------------------------------------------------------------
@@ -341,12 +257,6 @@ titleField = mapContext takeBaseName . pathField
341257-- that begins with @yyyy-mm-dd@ . For example:
342258-- @folder//yyyy-mm-dd-title//dist//main.extension@ .
343259-- 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.
350260
351261dateField :: String -- ^ Key in which the rendered date should be placed
352262 -> String -- ^ Format to use on the date
@@ -357,7 +267,7 @@ dateField = dateFieldWith defaultTimeLocale
357267--------------------------------------------------------------------------------
358268-- | This is an extended version of 'dateField' that allows you to
359269-- specify a time locale that is used for outputting the date. For more
360−-- details, see 'dateField' and 'formatTime'.
270+-- details, see 'dateField'.
361271dateFieldWith :: TimeLocale -- ^ Output time locale
362272 -> String -- ^ Destination key
363273 -> String -- ^ Format to use on the date
@@ -378,13 +288,12 @@ getItemUTC :: MonadMetadata m
378288getItemUTC locale id' = do
379289 metadata <- getMetadata id'
380290 let tryField k fmt = lookupString k metadata >>= parseTime' fmt
381− paths = splitDirectories $ (dropExtension . toFilePath) id'
291+ paths = splitDirectories $ toFilePath id'
382292
383293 maybe empty' return $ msum $
384294 [tryField "published" fmt | fmt <- formats] ++
385295 [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]
296+ [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths]
388297 where
389298 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
390299 "could not parse time for " ++ show id'
@@ -412,16 +321,13 @@ getItemModificationTime identifier = do
412321
413322
414323--------------------------------------------------------------------------------
415−-- | Creates a field with the last modification date of the underlying item.
416324modificationTimeField :: String -- ^ Key
417325 -> String -- ^ Format
418− -> Context a -- ^ Resulting context
326+ -> Context a -- ^ Resuting context
419327modificationTimeField = modificationTimeFieldWith defaultTimeLocale
420328
421329
422330--------------------------------------------------------------------------------
423−-- | Creates a field with the last modification date of the underlying item
424−-- in a custom localisation format (see 'formatTime').
425331modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
426332 -> String -- ^ Key
427333 -> String -- ^ Format
@@ -460,11 +366,10 @@ teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
460366
461367
462368--------------------------------------------------------------------------------
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.
465369missingField :: Context a
466−missingField = Context $ \k _ _ -> noResult $
467− "Missing field '" ++ k ++ "' in context"
370+missingField = Context $ \k _ i -> fail $
371+ "Missing field $" ++ k ++ "$ in context for item " ++
372+ show (itemIdentifier i)
468373
469374parseTimeM :: Bool -> TimeLocale -> String -> String -> Maybe UTCTime
470375#if MIN_VERSION_time(1,5,0)
@@ -472,10 +377,3 @@ parseTimeM = TF.parseTimeM
472377#else
473378parseTimeM _ = TF.parseTime
474379#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