module Text.Hakyll.Render
( depends
, render
, renderAndConcat
, renderChain
, static
, css
) where
import Text.Template hiding (render)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Map as M
import Control.Monad (unless, liftM, foldM)
import System.Directory (copyFile)
import System.IO
import Text.Hakyll.Page
import Text.Hakyll.Renderable
import Text.Hakyll.File
import Text.Hakyll.CompressCSS
depends :: FilePath
-> [FilePath]
-> IO ()
-> IO ()
depends file dependencies action = do
valid <- isCacheValid (toDestination file) dependencies
unless valid action
render :: Renderable a
=> FilePath
-> a
-> IO Page
render templatePath renderable = do
handle <- openFile templatePath ReadMode
templateString <- liftM B.pack $ hGetContents handle
seq templateString $ hClose handle
context <- toContext renderable
let body = substitute templateString context
return $ fromContext (M.insert (B.pack "body") body context)
renderAndConcat :: Renderable a => FilePath -> [a] -> IO B.ByteString
renderAndConcat templatePath renderables = foldM concatRender' B.empty renderables
where concatRender' :: Renderable a => B.ByteString -> a -> IO B.ByteString
concatRender' chunk renderable = do
rendered <- render templatePath renderable
let body = getBody rendered
return $ B.append chunk $ body
renderChain :: Renderable a => [FilePath] -> a -> IO ()
renderChain templates renderable =
depends (getURL renderable) (getDependencies renderable ++ templates) $
do initialPage <- toContext renderable
result <- foldM (flip render) (fromContext initialPage) templates
writePage result
static :: FilePath -> IO ()
static source = depends destination [source]
(makeDirectories destination >> copyFile source destination)
where destination = toDestination source
css :: FilePath -> IO ()
css source = depends destination [source] css'
where destination = toDestination source
css' = do h <- openFile source ReadMode
contents <- hGetContents h
makeDirectories destination
writeFile destination (compressCSS contents)