summaryrefslogtreecommitdiff
path: root/src/Text/Hakyll/Render.hs
blob: 2d09d4257fb0c761c829e30ea947b8e3770edf36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module Text.Hakyll.Render 
    ( renderPage,
      renderAndWrite,
      static,
      staticDirectory
    ) where

import Text.Template
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Map as M
import Control.Monad

import System.FilePath
import System.Directory
import System.IO

import Text.Hakyll.Page
import Text.Hakyll.Util

toDestination :: FilePath -> FilePath
toDestination path = "_site" </> path

createContext :: Page -> Context
createContext = M.fromList . map packPair . M.toList
    where packPair (a, b) = (B.pack a, b)

renderPage :: FilePath -> Page -> IO Page
renderPage templatePath page = do
    handle <- openFile templatePath ReadMode
    templateString <- liftM B.pack $ hGetContents handle
    seq templateString $ hClose handle
    let body = substitute templateString (createContext page)
    return $ addContext "body" (B.unpack body) page

renderAndWrite :: FilePath -> Page -> IO ()
renderAndWrite templatePath page = do
    rendered <- renderPage templatePath page
    let destination = toDestination $ getURL rendered
    makeDirectories destination
    B.writeFile destination (getBody rendered)

static :: FilePath -> IO ()
static source = do
    makeDirectories destination
    copyFile source destination
    where destination = toDestination source

staticDirectory :: FilePath -> IO ()
staticDirectory dir = 
    getRecursiveContents dir >>= mapM_ static