on master help sign in
Add requireApplyTemplate and applySelf utilities
commit6b4c65642e21684bc143eaf29453d1d99fd9e227 authorJasper Van der Jeugt <m@jaspervdj.be> dateWed 21 Nov 2012, 09:26 (14 years ago) parent815c265
3 files changed+38
src/Hakyll/Web/Template.hs+36 tests/data/template.html+1 tests/data/template.html.out+1
src/Hakyll/Web/Template.hs+36
@@ -40,6 +40,8 @@ module Hakyll.Web.Template
4040 ( Template
4141 , templateCompiler
4242 , applyTemplate
43+ , requireApplyTemplate
44+ , applySelf
4345 , applyTemplateWith
4446 ) where
4547
@@ -51,6 +53,7 @@ import Prelude hiding (id)
5153
5254--------------------------------------------------------------------------------
5355import Hakyll.Core.Compiler
56+import Hakyll.Core.Identifier
5457import Hakyll.Core.Item
5558import Hakyll.Web.Template.Context
5659import Hakyll.Web.Template.Internal
@@ -77,6 +80,39 @@ applyTemplate tpl context item = do
7780
7881
7982--------------------------------------------------------------------------------
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.
80116applyTemplateWith :: Monad m
81117 => (String -> a -> m String)
82118 -> Template -> a -> m String
tests/data/template.html+1
@@ -1,4 +1,5 @@
11<div>
2+ I'm so rich I have $$3.
23 $echo test$
34 $body$
45</div>
tests/data/template.html.out+1
@@ -1,4 +1,5 @@
11<div>
2+ I'm so rich I have $3.
23 test
34 <p>This is an example.</p>
45</div>