on master help sign in
Add requireApplyTemplate and applySelf utilities
6b4c656Jasper Van der Jeugt
src/Hakyll/Web/Template.hs+36
@@ -40,6 +40,8 @@ module Hakyll.Web.Template
40 ( Template
40 ( Template
41 , templateCompiler
41 , templateCompiler
42 , applyTemplate
42 , applyTemplate
43+ , requireApplyTemplate
44+ , applySelf
43 , applyTemplateWith
45 , applyTemplateWith
44 ) where
46 ) where
45
47
@@ -51,6 +53,7 @@ import Prelude hiding (id)
51
53
52--------------------------------------------------------------------------------
54--------------------------------------------------------------------------------
53import Hakyll.Core.Compiler
55import Hakyll.Core.Compiler
56+import Hakyll.Core.Identifier
54import Hakyll.Core.Item
57import Hakyll.Core.Item
55import Hakyll.Web.Template.Context
58import Hakyll.Web.Template.Context
56import Hakyll.Web.Template.Internal
59import Hakyll.Web.Template.Internal
@@ -77,6 +80,39 @@ applyTemplate tpl context item = do
77
80
78
81
79--------------------------------------------------------------------------------
82--------------------------------------------------------------------------------
83+-- | The following pattern is so common:
84+--
85+-- > tpl <- requireBody "templates/foo.html"
86+-- > someCompiler
87+-- > >>= applyTemplate tpl context
88+--
89+-- That we have a single function which does this:
90+--
91+-- > someCompiler
92+-- > >>= requireApplyTemplate "templates/foo.html" context
93+requireApplyTemplate :: Identifier -- ^ Template identifier
94+ -> Context a -- ^ Context
95+ -> Item a -- ^ Page
96+ -> Compiler (Item String) -- ^ Resulting item
97+requireApplyTemplate identifier context item = do
98+ tpl <- requireBody identifier
99+ applyTemplate tpl context item
100+
101+
102+--------------------------------------------------------------------------------
103+-- | It is also possible that you want to substitute @$key$@s within the body of
104+-- an item. This function does that by interpreting the item body as a template,
105+-- and then applying it to itself.
106+applySelf :: Context String -- ^ Context
107+ -> Item String -- ^ Item and template
108+ -> Compiler (Item String) -- ^ Resulting item
109+applySelf context item =
110+ let tpl = readTemplate $ itemBody item
111+ in applyTemplate tpl context item
112+
113+
114+--------------------------------------------------------------------------------
115+-- | Overloaded apply template function to work in an arbitrary Monad.
80applyTemplateWith :: Monad m
116applyTemplateWith :: Monad m
81 => (String -> a -> m String)
117 => (String -> a -> m String)
82 -> Template -> a -> m String
118 -> Template -> a -> m String
tests/data/template.html+1
@@ -1,4 +1,5 @@
1<div>
1<div>
2+ I'm so rich I have $$3.
2 $echo test$
3 $echo test$
3 $body$
4 $body$
4</div>
5</div>
tests/data/template.html.out+1
@@ -1,4 +1,5 @@
1<div>
1<div>
2+ I'm so rich I have $3.
2 test
3 test
3 <p>This is an example.</p>
4 <p>This is an example.</p>
4</div>
5</div>