Debian Codegraph @

lib/Hakyll/Web/Template/Internal.hs

raw
1 {-# LANGUAGE DeriveAnyClass #-}
2 {-# LANGUAGE DeriveGeneric #-}
3 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
4 {-# LANGUAGE ScopedTypeVariables #-}
5
6 module Hakyll.Web.Template.Internal
7 ( Template (..)
8 , template
9 , templateBodyCompiler
10 , templateCompiler
11 , applyTemplate
12 , loadAndApplyTemplate
13 , applyAsTemplate
14 , readTemplate
15 , compileTemplateItem
16 , unsafeReadTemplateFile
17
18 , module Hakyll.Web.Template.Internal.Element
19 , module Hakyll.Web.Template.Internal.Trim
20 ) where
21
22
23 --------------------------------------------------------------------------------
24 import Control.Monad.Except (catchError)
25 import Data.Binary (Binary)
26 import Data.List (intercalate)
27 import qualified Data.List.NonEmpty as NonEmpty
28 import Data.Typeable (Typeable)
29 import GHC.Exts (IsString (..))
30 import GHC.Generics (Generic)
31
32
33 --------------------------------------------------------------------------------
34 import Hakyll.Core.Compiler
35 import Hakyll.Core.Compiler.Internal
36 import Hakyll.Core.Identifier
37 import Hakyll.Core.Item
38 import Hakyll.Core.Writable
39 import Hakyll.Web.Template.Context
40 import Hakyll.Web.Template.Internal.Element
41 import Hakyll.Web.Template.Internal.Trim
42
43
44 --------------------------------------------------------------------------------
45 -- | Datatype used for template substitutions.
46 data Template = Template
47 { tplElements :: [TemplateElement]
48 , tplOrigin :: FilePath -- Only for error messages.
49 } deriving (Show, Eq, Generic, Binary, Typeable)
50
51
52 --------------------------------------------------------------------------------
53 instance Writable Template where
54 -- Writing a template is impossible
55 write _ _ = return ()
56
57
58 --------------------------------------------------------------------------------
59 instance IsString Template where
60 fromString = readTemplate
61
62
63 --------------------------------------------------------------------------------
64 -- | Wrap the constructor to ensure trim is called.
65 template :: FilePath -> [TemplateElement] -> Template
66 template p = flip Template p . trim
67
68
69 --------------------------------------------------------------------------------
70 -- | Parse a string into a template.
71 -- You should prefer 'compileTemplateItem' over this.
72 readTemplate :: String -> Template
73 readTemplate = either error (template origin) . parseTemplateElemsFile origin
74 where
75 origin = "{literal}"
76 {-# DEPRECATED readTemplate "Use templateCompiler instead" #-}
77
78 --------------------------------------------------------------------------------
79 -- | Parse an item body into a template.
80 -- Provides useful error messages in the 'Compiler' monad.
81 compileTemplateItem :: Item String -> Compiler Template
82 compileTemplateItem item = let file = itemIdentifier item
83 in compileTemplateFile file (itemBody item)
84
85 --------------------------------------------------------------------------------
86 compileTemplateFile :: Identifier -> String -> Compiler Template
87 compileTemplateFile file = either fail (return . template origin)
88 . parseTemplateElemsFile origin
89 where
90 origin = show file
91
92 --------------------------------------------------------------------------------
93 -- | Read a template, without metadata header
94 templateBodyCompiler :: Compiler (Item Template)
95 templateBodyCompiler = cached "Hakyll.Web.Template.templateBodyCompiler" $ do
96 item <- getResourceBody
97 file <- getUnderlying
98 withItemBody (compileTemplateFile file) item
99
100 --------------------------------------------------------------------------------
101 -- | Read complete file contents as a template
102 templateCompiler :: Compiler (Item Template)
103 templateCompiler = cached "Hakyll.Web.Template.templateCompiler" $ do
104 item <- getResourceString
105 file <- getUnderlying
106 withItemBody (compileTemplateFile file) item
107
108
109 --------------------------------------------------------------------------------
110 -- | Interpolate template expressions from context values in a page
111 applyTemplate :: Template -- ^ Template
112 -> Context a -- ^ Context
113 -> Item a -- ^ Page
114 -> Compiler (Item String) -- ^ Resulting item
115 applyTemplate tpl context item = do
116 body <- applyTemplate' (tplElements tpl) context item `catchError` handler
117 return $ itemSetBody body item
118 where
119 tplName = tplOrigin tpl
120 itemName = show $ itemIdentifier item
121 handler es = fail $ "Hakyll.Web.Template.applyTemplate: Failed to " ++
122 (if tplName == itemName
123 then "interpolate template in item " ++ itemName
124 else "apply template " ++ tplName ++ " to item " ++ itemName) ++
125 ":\n" ++ intercalate ",\n" es
126
127
128
129 --------------------------------------------------------------------------------
130 applyTemplate'
131 :: forall a.
132 [TemplateElement] -- ^ Unwrapped Template
133 -> Context a -- ^ Context
134 -> Item a -- ^ Page
135 -> Compiler String -- ^ Resulting item
136 applyTemplate' tes context x = go tes
137 where
138 context' :: String -> [String] -> Item a -> Compiler ContextField
139 context' = unContext (context `mappend` missingField)
140
141 go = fmap concat . mapM applyElem
142
143 ---------------------------------------------------------------------------
144
145 applyElem :: TemplateElement -> Compiler String
146
147 applyElem TrimL = trimError
148
149 applyElem TrimR = trimError
150
151 applyElem (Chunk c) = return c
152
153 applyElem (Expr e) = withErrorMessage evalMsg (applyStringExpr typeMsg e)
154 where
155 evalMsg = "In expr '$" ++ show e ++ "$'"
156 typeMsg = "expr '$" ++ show e ++ "$'"
157
158 applyElem Escaped = return "$"
159
160 applyElem (If e t mf) = compilerTry (applyExpr e) >>= handle
161 where
162 f = maybe (return "") go mf
163 handle (Right _) = go t
164 handle (Left (CompilationNoResult _)) = f
165 handle (Left (CompilationFailure es)) = debug (NonEmpty.toList es) >> f
166 debug = compilerDebugEntries ("Hakyll.Web.Template.applyTemplate: " ++
167 "[ERROR] in 'if' condition on expr '" ++ show e ++ "':")
168
169 applyElem (For e b s) = withErrorMessage headMsg (applyExpr e) >>= \cf -> case cf of
170 EmptyField -> expected "list" "boolean" typeMsg
171 StringField _ -> expected "list" "string" typeMsg
172 ListField c xs -> withErrorMessage bodyMsg $ do
173 sep <- maybe (return "") go s
174 bs <- mapM (applyTemplate' b c) xs
175 return $ intercalate sep bs
176 where
177 headMsg = "In expr '$for(" ++ show e ++ ")$'"
178 typeMsg = "loop expr '" ++ show e ++ "'"
179 bodyMsg = "In loop context of '$for(" ++ show e ++ ")$'"
180
181 applyElem (Partial e) = withErrorMessage headMsg $
182 applyStringExpr typeMsg e >>= \p ->
183 withErrorMessage inclMsg $ do
184 tpl' <- loadBody (fromFilePath p)
185 itemBody <$> applyTemplate tpl' context x
186 where
187 headMsg = "In expr '$partial(" ++ show e ++ ")$'"
188 typeMsg = "partial expr '" ++ show e ++ "'"
189 inclMsg = "In inclusion of '$partial(" ++ show e ++ ")$'"
190
191 ---------------------------------------------------------------------------
192
193 applyExpr :: TemplateExpr -> Compiler ContextField
194
195 applyExpr (Ident (TemplateKey k)) = context' k [] x
196
197 applyExpr (Call (TemplateKey k) args) = do
198 args' <- mapM (\e -> applyStringExpr (typeMsg e) e) args
199 context' k args' x
200 where
201 typeMsg e = "argument '" ++ show e ++ "'"
202
203 applyExpr (StringLiteral s) = return (StringField s)
204
205 ----------------------------------------------------------------------------
206
207 applyStringExpr :: String -> TemplateExpr -> Compiler String
208 applyStringExpr msg expr =
209 applyExpr expr >>= getString
210 where
211 getString EmptyField = expected "string" "boolean" msg
212 getString (StringField s) = return s
213 getString (ListField _ _) = expected "string" "list" msg
214
215 expected typ act expr = fail $ unwords ["Hakyll.Web.Template.applyTemplate:",
216 "expected", typ, "but got", act, "for", expr]
217
218 -- expected to never happen with all templates constructed by 'template'
219 trimError = fail $
220 "Hakyll.Web.Template.applyTemplate: template not fully trimmed."
221
222
223 --------------------------------------------------------------------------------
224 -- | The following pattern is so common:
225 --
226 -- > tpl <- loadBody "templates/foo.html"
227 -- > someCompiler
228 -- > >>= applyTemplate tpl context
229 --
230 -- That we have a single function which does this:
231 --
232 -- > someCompiler
233 -- > >>= loadAndApplyTemplate "templates/foo.html" context
234 loadAndApplyTemplate :: Identifier -- ^ Template identifier
235 -> Context a -- ^ Context
236 -> Item a -- ^ Page
237 -> Compiler (Item String) -- ^ Resulting item
238 loadAndApplyTemplate identifier context item = do
239 tpl <- loadBody identifier
240 applyTemplate tpl context item
241
242
243 --------------------------------------------------------------------------------
244 -- | It is also possible that you want to substitute @$key$@s within the body of
245 -- an item. This function does that by interpreting the item body as a template,
246 -- and then applying it to itself.
247 applyAsTemplate :: Context String -- ^ Context
248 -> Item String -- ^ Item and template
249 -> Compiler (Item String) -- ^ Resulting item
250 applyAsTemplate context item = do
251 tpl <- compileTemplateItem item
252 applyTemplate tpl context item
253
254
255 --------------------------------------------------------------------------------
256 unsafeReadTemplateFile :: FilePath -> Compiler Template
257 unsafeReadTemplateFile file = do
258 tpl <- unsafeCompiler $ readFile file
259 compileTemplateFile (fromFilePath file) tpl
260 {-# DEPRECATED unsafeReadTemplateFile "Use templateCompiler" #-}