Debian Codegraph @

lib/Hakyll/Web/Template/Context.hs

raw
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 strings 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 the path,
18 -- and include the referenced file as a template.
19
20
21 --------------------------------------------------------------------------------
22 {-# LANGUAGE CPP #-}
23 {-# LANGUAGE ExistentialQuantification #-}
24 module Hakyll.Web.Template.Context
25 ( ContextField (..)
26 , Context (..)
27 , field
28 , boolField
29 , boolFieldM
30 , constField
31 , listField
32 , listFieldWith
33 , functionField
34 , mapContext
35 , mapContextBy
36
37 , defaultContext
38 , bodyField
39 , metadataField
40 , urlField
41 , pathField
42 , titleField
43 , snippetField
44 , dateField
45 , dateFieldWith
46 , getItemUTC
47 , getItemModificationTime
48 , modificationTimeField
49 , modificationTimeFieldWith
50 , teaserField
51 , teaserFieldWithSeparator
52 , missingField
53 ) where
54
55
56 --------------------------------------------------------------------------------
57 import Control.Applicative (Alternative (..))
58 import Control.Monad (msum)
59 #if !MIN_VERSION_base(4,13,0)
60 import Control.Monad.Fail (MonadFail)
61 #endif
62 import Data.Functor.Contravariant (Contravariant (..))
63 import Data.Functor.Contravariant.Divisible (Divisible (..), Decidable (..))
64 import Data.List (intercalate, tails)
65 import Data.Time.Clock (UTCTime (..))
66 import Data.Time.Format (formatTime, parseTimeM)
67 import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
68 import Hakyll.Core.Compiler
69 import Hakyll.Core.Compiler.Internal
70 import Hakyll.Core.Identifier
71 import Hakyll.Core.Item
72 import Hakyll.Core.Metadata
73 import Hakyll.Core.Provider
74 import Hakyll.Core.Util.String (needlePrefix, splitAll)
75 import Hakyll.Web.Html
76 import Prelude hiding (id)
77 import System.FilePath (dropExtension, splitDirectories,
78 takeBaseName)
79
80 --------------------------------------------------------------------------------
81 -- | Mostly for internal usage
82 data ContextField
83 = EmptyField
84 | StringField String
85 | forall a. ListField (Context a) [Item a]
86
87
88 --------------------------------------------------------------------------------
89 -- | The 'Context' monoid. Please note that the order in which you
90 -- compose the items is important. For example in
91 --
92 -- > field "A" f1 <> field "A" f2
93 --
94 -- the first context will overwrite the second. This is especially
95 -- important when something is being composed with
96 -- 'metadataField' (or 'defaultContext'). If you want your context to be
97 -- overwritten by the metadata fields, compose it from the right:
98 --
99 -- @
100 -- 'metadataField' \<\> field \"date\" fDate
101 -- @
102 --
103 newtype Context a = Context
104 { unContext :: String -> [String] -> Item a -> Compiler ContextField
105 }
106
107
108 --------------------------------------------------------------------------------
109 -- | Tries to find a key in the left context,
110 -- or when that fails in the right context.
111 instance Semigroup (Context a) where
112 (<>) (Context f) (Context g) = Context $ \k a i -> f k a i <|> g k a i
113
114 instance Monoid (Context a) where
115 mempty = missingField
116 mappend = (<>)
117
118 instance Contravariant Context where
119 contramap f ctx = Context (\s ss -> unContext ctx s ss . fmap f)
120
121 instance Divisible Context where
122 divide f c1 c2 = contramap (fst . f) c1 <> contramap (snd . f) c2
123 conquer = missingField
124
125 instance Decidable Context where
126 choose f (Context c1) (Context c2) = Context (\s ss (Item i e) ->
127 either (c1 s ss . Item i) (c2 s ss . Item i) (f e))
128 lose f = contramap f missingField
129
130 --------------------------------------------------------------------------------
131 field' :: String -> (Item a -> Compiler ContextField) -> Context a
132 field' key value = Context $ \k _ i ->
133 if k == key
134 then value i
135 else noResult $ "Tried field " ++ key
136
137
138 --------------------------------------------------------------------------------
139 -- | Constructs a new field for a 'Context'.
140 -- If the key matches, the compiler is run and its result is substituted in the
141 -- template.
142 --
143 -- If the compiler fails, the field will be considered non-existent
144 -- in an @$if()$@ macro or ultimately break the template application
145 -- (unless the key is found in another context when using '<>').
146 -- Use 'empty' or 'noResult' for intentional failures of fields used in
147 -- @$if()$@, to distinguish them from exceptions thrown with 'fail'.
148 field
149 :: String -- ^ Key
150 -> (Item a -> Compiler String) -- ^ Function that constructs a value based
151 -- on the item (e.g. accessing metadata)
152 -> Context a
153 field key value = field' key (fmap StringField . value)
154
155
156 --------------------------------------------------------------------------------
157 -- | Creates a 'field' to use with the @$if()$@ template macro.
158 -- Attempting to substitute the field into the template will cause an error.
159 boolField
160 :: String -- ^ Key
161 -> (Item a -> Bool) -- ^ Extract value from an @'Item' a@
162 -> Context a
163 boolField name f = boolFieldM name (pure . f)
164
165
166 --------------------------------------------------------------------------------
167 -- | Creates a 'field' to use with the @$if()$@ template macro, in the
168 -- 'Compiler' monad. Attempting to substitute the field into the template
169 -- will cause an error.
170 --
171 -- @since 4.16.4.0
172 boolFieldM
173 :: String -- ^ Key
174 -> (Item a -> Compiler Bool) -- ^ Extract value from an @'Item' a@
175 -- from within the 'Compiler' monad
176 -> Context a
177 boolFieldM name f = field' name (\i -> do
178 b <- f i
179 if b
180 then return EmptyField
181 else noResult $ "Field " ++ name ++ " is false")
182
183
184 --------------------------------------------------------------------------------
185 -- | Creates a 'field' that does not depend on the 'Item' but always yields
186 -- the same string
187 constField :: String -- ^ Key
188 -> String -- ^ Value
189 -> Context a
190 constField key = field key . const . return
191
192
193 --------------------------------------------------------------------------------
194 -- | Creates a list field to be consumed by a @$for(…)$@ expression.
195 -- The compiler returns multiple items which are rendered in the loop body
196 -- with the supplied context.
197 listField :: String -> Context a -> Compiler [Item a] -> Context b
198 listField key c xs = listFieldWith key c (const xs)
199
200
201 --------------------------------------------------------------------------------
202 -- | Creates a list field like 'listField', but supplies the current page
203 -- to the compiler.
204 listFieldWith
205 :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
206 listFieldWith key c f = field' key $ fmap (ListField c) . f
207
208
209 --------------------------------------------------------------------------------
210 -- | Creates a variadic function field.
211 --
212 -- The function will be called with the dynamically evaluated string arguments
213 -- from the template as well as the page that is currently rendered.
214 functionField :: String -- ^ Key
215 -> ([String] -> Item a -> Compiler String) -- ^ Function
216 -> Context a
217 functionField name value = Context $ \k args i ->
218 if k == name
219 then StringField <$> value args i
220 else noResult $ "Tried function field " ++ name
221
222
223 --------------------------------------------------------------------------------
224 -- | Transform the respective string results of all fields in a context.
225 -- For example,
226 --
227 -- > mapContext (++"c") (constField "x" "a" <> constField "y" "b")
228 --
229 -- is equivalent to
230 --
231 -- > constField "x" "ac" <> constField "y" "bc"
232 --
233 mapContext :: (String -> String) -> Context a -> Context a
234 mapContext = mapContextBy (const True)
235
236
237 --------------------------------------------------------------------------------
238 -- | Transform the respective string results of all fields in a context
239 -- satisfying a predicate. For example,
240 --
241 -- > mapContextBy (=="y") (++"c") (constField "x" "a" <> constField "y" "b")
242 --
243 -- is equivalent to
244 --
245 -- > constField "x" "a" <> constField "y" "bc"
246 --
247 mapContextBy :: (String -> Bool) -> (String -> String) -> Context a -> Context a
248 mapContextBy p f (Context c) = Context $ \k a i -> do
249 fld <- c k a i
250 case fld of
251 EmptyField -> wrongType "boolField"
252 StringField str -> return $ StringField $
253 if p k then f str else str
254 _ -> wrongType "ListField"
255 where
256 wrongType typ = fail $ "Hakyll.Web.Template.Context.mapContext: " ++
257 "can't map over a " ++ typ ++ "!"
258
259 --------------------------------------------------------------------------------
260 -- | A context that allows snippet inclusion. In processed file, use as:
261 --
262 -- > ...
263 -- > $snippet("path/to/snippet/")$
264 -- > ...
265 --
266 -- The contents of the included file will not be interpolated like @partial@
267 -- does it.
268 --
269 snippetField :: Context String
270 snippetField = functionField "snippet" f
271 where
272 f [contentsPath] _ = loadBody (fromFilePath contentsPath)
273 f [] _ = fail "No argument to function 'snippet()'"
274 f _ _ = fail "Too many arguments to function 'snippet()'"
275
276 --------------------------------------------------------------------------------
277 -- | A context that contains (in that order)
278 --
279 -- 1. A @$body$@ 'bodyField'
280 --
281 -- 2. Metadata fields
282 --
283 -- 3. A @$url$@ 'urlField'
284 --
285 -- 4. A @$path$@ 'pathField'
286 --
287 -- 5. A @$title$@ 'titleField'
288 --
289 -- This order means that all of the fields, except @$body$@,
290 -- can have their values replaced by metadata fields of the same name.
291 -- For example, a context from a file at @posts/foo.markdown@ has a default title
292 -- @foo@. However, with a metadata field:
293 --
294 -- > ---
295 -- > title: The Foo Story
296 -- > ---
297 --
298 -- The @$title$@ will be replaced with @The Foo Story@.
299 defaultContext :: Context String
300 defaultContext =
301 bodyField "body" `mappend`
302 metadataField `mappend`
303 urlField "url" `mappend`
304 pathField "path" `mappend`
305 titleField "title"
306
307
308 --------------------------------------------------------------------------------
309 teaserSeparator :: String
310 teaserSeparator = "<!--more-->"
311
312
313 --------------------------------------------------------------------------------
314 -- | Body of the item, that is, the main content of the underlying file
315 bodyField :: String -> Context String
316 bodyField key = field key $ return . itemBody
317
318
319 --------------------------------------------------------------------------------
320 -- | Map any field to its metadata value, if present
321 metadataField :: Context a
322 metadataField = Context $ \k _ i -> do
323 let id = itemIdentifier i
324 empty' = noResult $ "No '" ++ k ++ "' field in metadata " ++
325 "of item " ++ show id
326 value <- getMetadataField id k
327 maybe empty' (return . StringField) value
328
329
330 --------------------------------------------------------------------------------
331 -- | Absolute url to the resulting item. For an example item that produces a
332 -- file @posts/foo.html@, this field contains "posts/foo.html"
333 urlField :: String -> Context a
334 urlField key = field key $ \i -> do
335 let id = itemIdentifier i
336 empty' = fail $ "No route url found for item " ++ show id
337 fmap (maybe empty' toUrl) $ getRoute id
338
339
340 --------------------------------------------------------------------------------
341 -- | Filepath of the underlying file of the item. For an example
342 -- underlying file @posts/foo.markdown@, this field contains
343 -- "posts/foo.markdown"
344 pathField :: String -> Context a
345 pathField key = field key $ return . toFilePath . itemIdentifier
346
347
348 --------------------------------------------------------------------------------
349 -- | Basename of the underlying file of the item. For an example
350 -- underlying file @posts/foo.markdown@, this field contains "foo"
351 titleField :: String -> Context a
352 titleField = mapContext takeBaseName . pathField
353
354
355 --------------------------------------------------------------------------------
356 -- | When the metadata has a field called @published@ in one of the
357 -- following formats then this function can render the date.
358 --
359 -- * @Mon, 06 Sep 2010 00:01:00 +0000@
360 --
361 -- * @Mon, 06 Sep 2010 00:01:00 UTC@
362 --
363 -- * @Mon, 06 Sep 2010 00:01:00@
364 --
365 -- * @2010-09-06T00:01:00+0000@
366 --
367 -- * @2010-09-06T00:01:00Z@
368 --
369 -- * @2010-09-06T00:01:00@
370 --
371 -- * @2010-09-06 00:01:00+0000@
372 --
373 -- * @2010-09-06 00:01:00@
374 --
375 -- * @September 06, 2010 00:01 AM@
376 --
377 -- Following date-only formats are supported too (@00:00:00@ for time is
378 -- assumed)
379 --
380 -- * @2010-09-06@
381 --
382 -- * @06.09.2010@
383 --
384 -- * @September 06, 2010@
385 --
386 -- Alternatively, when the metadata has a field called @path@ in a
387 -- @folder/yyyy-mm-dd-title.extension@ format (the convention for pages)
388 -- and no @published@ metadata field set, this function can render
389 -- the date. This pattern matches the file name or directory names
390 -- that begins with @yyyy-mm-dd@ . For example:
391 -- @folder//yyyy-mm-dd-title//dist//main.extension@ .
392 -- In case of multiple matches, the rightmost one is used.
393 --
394 -- As another alternative, if none of the above matches, and the file has a
395 -- path which contains nested directories specifying a date, then that date
396 -- will be used. In other words, if the path is of the form
397 -- @**//yyyy//mm//dd//**//main.extension@ .
398 -- As above, in case of multiple matches, the rightmost one is used.
399
400 dateField :: String -- ^ Key in which the rendered date should be placed
401 -> String -- ^ Format to use on the date
402 -> Context a -- ^ Resulting context
403 dateField = dateFieldWith defaultTimeLocale
404
405
406 --------------------------------------------------------------------------------
407 -- | This is an extended version of 'dateField' that allows you to
408 -- specify a time locale that is used for outputting the date. For more
409 -- details, see 'dateField' and 'formatTime'.
410 dateFieldWith :: TimeLocale -- ^ Output time locale
411 -> String -- ^ Destination key
412 -> String -- ^ Format to use on the date
413 -> Context a -- ^ Resulting context
414 dateFieldWith locale key format = field key $ \i -> do
415 time <- getItemUTC locale $ itemIdentifier i
416 return $ formatTime locale format time
417
418
419 --------------------------------------------------------------------------------
420 -- | Parser to try to extract and parse the time from the @published@
421 -- field or from the filename. See 'dateField' for more information.
422 -- Exported for user convenience.
423 getItemUTC :: (MonadMetadata m, MonadFail m)
424 => TimeLocale -- ^ Output time locale
425 -> Identifier -- ^ Input page
426 -> m UTCTime -- ^ Parsed UTCTime
427 getItemUTC locale id' = do
428 metadata <- getMetadata id'
429 let tryField k fmt = lookupString k metadata >>= parseTime' fmt
430 paths = splitDirectories $ (dropExtension . toFilePath) id'
431
432 maybe empty' return $ msum $
433 [tryField "published" fmt | fmt <- formats] ++
434 [tryField "date" fmt | fmt <- formats] ++
435 [parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fnCand | fnCand <- reverse paths] ++
436 [parseTime' "%Y-%m-%d" $ intercalate "-" $ fnCand | fnCand <- map (take 3) $ reverse . tails $ paths]
437 where
438 empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
439 "could not parse time for " ++ show id'
440 parseTime' = parseTimeM True locale
441 formats =
442 [ "%a, %d %b %Y %H:%M:%S %Z"
443 , "%a, %d %b %Y %H:%M:%S"
444 , "%Y-%m-%dT%H:%M:%S%Z"
445 , "%Y-%m-%dT%H:%M:%S"
446 , "%Y-%m-%d %H:%M:%S%Z"
447 , "%Y-%m-%d %H:%M:%S"
448 , "%Y-%m-%d"
449 , "%d.%m.%Y"
450 , "%B %e, %Y %l:%M %p"
451 , "%B %e, %Y"
452 , "%b %d, %Y"
453 ]
454
455
456 --------------------------------------------------------------------------------
457 -- | Get the time on which the actual file was last modified. This only works if
458 -- there actually is an underlying file, of couse.
459 getItemModificationTime
460 :: Identifier
461 -> Compiler UTCTime
462 getItemModificationTime identifier = do
463 provider <- compilerProvider <$> compilerAsk
464 return $ resourceModificationTime provider identifier
465
466
467 --------------------------------------------------------------------------------
468 -- | Creates a field with the last modification date of the underlying item.
469 modificationTimeField :: String -- ^ Key
470 -> String -- ^ Format
471 -> Context a -- ^ Resulting context
472 modificationTimeField = modificationTimeFieldWith defaultTimeLocale
473
474
475 --------------------------------------------------------------------------------
476 -- | Creates a field with the last modification date of the underlying item
477 -- in a custom localisation format (see 'formatTime').
478 modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
479 -> String -- ^ Key
480 -> String -- ^ Format
481 -> Context a -- ^ Resulting context
482 modificationTimeFieldWith locale key fmt = field key $ \i -> do
483 mtime <- getItemModificationTime $ itemIdentifier i
484 return $ formatTime locale fmt mtime
485
486
487 --------------------------------------------------------------------------------
488 -- | A context with "teaser" key which contain a teaser of the item.
489 -- The item is loaded from the given snapshot (which should be saved
490 -- in the user code before any templates are applied).
491 teaserField :: String -- ^ Key to use
492 -> Snapshot -- ^ Snapshot to load
493 -> Context String -- ^ Resulting context
494 teaserField = teaserFieldWithSeparator teaserSeparator
495
496
497 --------------------------------------------------------------------------------
498 -- | A context with "teaser" key which contain a teaser of the item, defined as
499 -- the snapshot content before the teaser separator. The item is loaded from the
500 -- given snapshot (which should be saved in the user code before any templates
501 -- are applied).
502 teaserFieldWithSeparator :: String -- ^ Separator to use
503 -> String -- ^ Key to use
504 -> Snapshot -- ^ Snapshot to load
505 -> Context String -- ^ Resulting context
506 teaserFieldWithSeparator separator key snapshot = field key $ \item -> do
507 body <- itemBody <$> loadSnapshot (itemIdentifier item) snapshot
508 case needlePrefix separator body of
509 Nothing -> fail $
510 "Hakyll.Web.Template.Context: no teaser defined for " ++
511 show (itemIdentifier item)
512 Just t -> return t
513
514
515 --------------------------------------------------------------------------------
516 -- | Constantly reports any field as missing. Mostly for internal usage,
517 -- it is the last choice in every context used in a template application.
518 missingField :: Context a
519 missingField = Context $ \k _ _ -> noResult $
520 "Missing field '" ++ k ++ "' in context"