@@ -1,6 +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--------------------------------------------------------------------------------
222{-# LANGUAGE CPP #-}
323{-# LANGUAGE ExistentialQuantification #-}
24+{-# LANGUAGE RankNTypes #-}
425module Hakyll.Web.Template.Context
526 ( ContextField (..)
627 , Context (..)
@@ -28,13 +49,14 @@ module Hakyll.Web.Template.Context
2849 , teaserField
2950 , teaserFieldWithSeparator
3051 , missingField
52+ , bindItem
3153 ) where
3254
3355
3456--------------------------------------------------------------------------------
3557import Control.Applicative (Alternative (..))
3658import Control.Monad (msum)
37−import Data.List (intercalate)
59+import Data.List (intercalate, tails)
3860#if MIN_VERSION_base(4,9,0)
3961import Data.Semigroup (Semigroup (..))
4062#endif
@@ -50,13 +72,16 @@ import Hakyll.Core.Metadata
5072import Hakyll.Core.Provider
5173import Hakyll.Core.Util.String (needlePrefix, splitAll)
5274import Hakyll.Web.Html
53−import System.FilePath (splitDirectories, takeBaseName, dropExtension)
75+import Prelude hiding (id)
76+import System.FilePath (dropExtension, splitDirectories,
77+ takeBaseName)
5478
5579
5680--------------------------------------------------------------------------------
5781-- | Mostly for internal usage
5882data ContextField
59− = StringField String
83+ = EmptyField
84+ | StringField String
6085 | forall a. ListField (Context a) [Item a]
6186
6287
@@ -81,6 +106,8 @@ newtype Context a = Context
81106
82107
83108--------------------------------------------------------------------------------
109+-- | Tries to find a key in the left context,
110+-- or when that fails in the right context.
84111#if MIN_VERSION_base(4,9,0)
85112instance Semigroup (Context a) where
86113 (<>) (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
@@ -97,64 +124,105 @@ instance Monoid (Context a) where
97124
98125--------------------------------------------------------------------------------
99126field' :: String -> (Item a -> Compiler ContextField) -> Context a
100−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
101131
102132
103133--------------------------------------------------------------------------------
104−-- | 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'.
105143field
106144 :: String -- ^ Key
107145 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
108− -- on the item
146+ -- on the item (e.g. accessing metadata)
109147 -> Context a
110148field key value = field' key (fmap StringField . value)
111149
112150
113151--------------------------------------------------------------------------------
114152-- | Creates a 'field' to use with the @$if()$@ template macro.
153+-- Attempting to substitute the field into the template will cause an error.
115154boolField
116155 :: String
117156 -> (Item a -> Bool)
118157 -> Context a
119−boolField name f = field name (\i -> if f i
120− then pure (error $ unwords ["no string value for bool field:",name])
121− else empty)
158+boolField name f = field' name (\i -> if f i
159+ then return EmptyField
160+ else noResult $ "Field " ++ name ++ " is false")
122161
123162
124163--------------------------------------------------------------------------------
125−-- | Creates a 'field' that does not depend on the 'Item'
126−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
127169constField key = field key . const . return
128170
129171
130172--------------------------------------------------------------------------------
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.
131176listField :: String -> Context a -> Compiler [Item a] -> Context b
132177listField key c xs = listFieldWith key c (const xs)
133178
134179
135180--------------------------------------------------------------------------------
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.
136187listFieldWith
137188 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
138189listFieldWith key c f = field' key $ fmap (ListField c) . f
139190
140191
141192--------------------------------------------------------------------------------
142−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
143200functionField name value = Context $ \k args i ->
144201 if k == name
145202 then StringField <$> value args i
146− else empty
203+ else noResult $ "Tried function field " ++ name
147204
148205
149206--------------------------------------------------------------------------------
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+--
150216mapContext :: (String -> String) -> Context a -> Context a
151217mapContext f (Context c) = Context $ \k a i -> do
152218 fld <- c k a i
153219 case fld of
220+ EmptyField -> wrongType "boolField"
154221 StringField str -> return $ StringField (f str)
155− ListField _ _ -> fail $
156− "Hakyll.Web.Template.Context.mapContext: " ++
157− "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 ++ "!"
158226
159227--------------------------------------------------------------------------------
160228-- | A context that allows snippet inclusion. In processed file, use as:
@@ -163,15 +231,15 @@ mapContext f (Context c) = Context $ \k a i -> do
163231-- > $snippet("path/to/snippet/")$
164232-- > ...
165233--
166−-- The contents of the included file will not be interpolated.
234+-- The contents of the included file will not be interpolated like @partial@
235+-- does it.
167236--
168237snippetField :: Context String
169238snippetField = functionField "snippet" f
170239 where
171240 f [contentsPath] _ = loadBody (fromFilePath contentsPath)
172− f _ i = error $
173− "Too many arguments to function 'snippet()' in item " ++
174− show (itemIdentifier i)
241+ f [] _ = fail "No argument to function 'snippet()'"
242+ f _ _ = fail "Too many arguments to function 'snippet()'"
175243
176244--------------------------------------------------------------------------------
177245-- | A context that contains (in that order)
@@ -191,8 +259,7 @@ defaultContext =
191259 metadataField `mappend`
192260 urlField "url" `mappend`
193261 pathField "path" `mappend`
194− titleField "title" `mappend`
195− missingField
262+ titleField "title"
196263
197264
198265--------------------------------------------------------------------------------
@@ -210,15 +277,20 @@ bodyField key = field key $ return . itemBody
210277-- | Map any field to its metadata value, if present
211278metadataField :: Context a
212279metadataField = Context $ \k _ i -> do
213− value <- getMetadataField (itemIdentifier i) k
214− 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
215285
216286
217287--------------------------------------------------------------------------------
218288-- | Absolute url to the resulting item
219289urlField :: String -> Context a
220−urlField key = field key $
221− 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
222294
223295
224296--------------------------------------------------------------------------------
@@ -269,6 +341,12 @@ titleField = mapContext takeBaseName . pathField
269341-- that begins with @yyyy-mm-dd@ . For example:
270342-- @folder//yyyy-mm-dd-title//dist//main.extension@ .
271343-- 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.
272350
273351dateField :: String -- ^ Key in which the rendered date should be placed
274352 -> String -- ^ Format to use on the date
@@ -279,7 +357,7 @@ dateField = dateFieldWith defaultTimeLocale
279357--------------------------------------------------------------------------------
280358-- | This is an extended version of 'dateField' that allows you to
281359-- specify a time locale that is used for outputting the date. For more
282−-- details, see 'dateField'.
360+-- details, see 'dateField' and 'formatTime'.
283361dateFieldWith :: TimeLocale -- ^ Output time locale
284362 -> String -- ^ Destination key
285363 -> String -- ^ Format to use on the date
@@ -305,7 +383,8 @@ getItemUTC locale id' = do
305383 maybe empty' return $ msum $
306384 [tryField "published" fmt | fmt <- formats] ++
307385 [tryField "date" fmt | fmt <- formats] ++
308− [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]
309388 where
310389 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
311390 "could not parse time for " ++ show id'
@@ -333,6 +412,7 @@ getItemModificationTime identifier = do
333412
334413
335414--------------------------------------------------------------------------------
415+-- | Creates a field with the last modification date of the underlying item.
336416modificationTimeField :: String -- ^ Key
337417 -> String -- ^ Format
338418 -> Context a -- ^ Resulting context
@@ -340,6 +420,8 @@ modificationTimeField = modificationTimeFieldWith defaultTimeLocale
340420
341421
342422--------------------------------------------------------------------------------
423+-- | Creates a field with the last modification date of the underlying item
424+-- in a custom localisation format (see 'formatTime').
343425modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
344426 -> String -- ^ Key
345427 -> String -- ^ Format
@@ -378,10 +460,11 @@ teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
378460
379461
380462--------------------------------------------------------------------------------
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.
381465missingField :: Context a
382−missingField = Context $ \k _ i -> fail $
383− "Missing field $" ++ k ++ "$ in context for item " ++
384− show (itemIdentifier i)
466+missingField = Context $ \k _ _ -> noResult $
467+ "Missing field '" ++ k ++ "' in context"
385468
386469parseTimeM :: Bool -> TimeLocale -> String -> String -> Maybe UTCTime
387470#if MIN_VERSION_time(1,5,0)
@@ -389,3 +472,10 @@ parseTimeM = TF.parseTimeM
389472#else
390473parseTimeM _ = TF.parseTime
391474#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