-- | Some utilities for common uses of Template Haskell. module Canteven.Template ( readFileAsStrLiteral, readFileAsMarkdown ) where import Data.Default (def) import Data.Functor ((<$>)) import Language.Haskell.TH (Exp, Q, runIO, stringE) import Language.Haskell.TH.Syntax (qAddDependentFile) import Text.Blaze.Html.Renderer.String (renderHtml) import Text.Markdown (markdown) import qualified Data.ByteString.Lazy as LBS import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE -- | Read a file from disk at compile time and provide it as a string literal. readFileAsStrLiteral :: FilePath -- ^ The compile-time location of the file to read. -> Q Exp readFileAsStrLiteral path = do qAddDependentFile path contents <- runIO $ readFile path stringE contents -- | Read a Markdown file from disk at compile time and render it as HTML. The -- resulting `Q Exp` is a string literal containing the HTML output. readFileAsMarkdown :: FilePath -- ^ The compile-time location of the file to read. -> Q Exp readFileAsMarkdown filename = do qAddDependentFile filename fileContent <- runIO $ TLE.decodeUtf8 <$> LBS.readFile filename stringE $ renderMarkdown fileContent where renderMarkdown :: TL.Text -> String renderMarkdown = renderHtml . markdown def