Skip to content

Instantly share code, notes, and snippets.

@tungd
Created November 17, 2017 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/12291fa3c7eb6864c1960305e45e82ee to your computer and use it in GitHub Desktop.
Save tungd/12291fa3c7eb6864c1960305e45e82ee to your computer and use it in GitHub Desktop.
Template Engine Test in Haskell. So far: Lucid is 10x faster than Mustache, and is 200x faster than EDE
#!/usr/bin/env stack
-- stack --resolver lts-9.13 --install-ghc runghc --package scotty
-- --package wai --package wai-middleware-prometheus --package warp --package text --package unix
-- --package lucid --package ede --package mustache
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.IO.Class
import Data.HashMap.Strict (fromList)
-- import Data.Aeson.Types
import Data.Monoid
import Data.Text (Text)
import Lucid
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Middleware.Prometheus
import Network.Wai.Middleware.RequestLogger
import System.Posix.Env
import Text.EDE (fromPairs, eitherParseFile, eitherRenderWith)
import Text.EDE.Filters ((@:))
import Text.Mustache
import Text.Mustache.Types (Pair)
import Web.Scotty hiding (settings)
import qualified Data.Text.Lazy as TL
data Env = Production | Development
deriving (Read)
data Config = Config
{ configEnv :: Env
, configPort :: Port
}
main :: IO ()
main = do
port :: Port <- read <$> getEnvDefault "PORT" "3000"
env <- env' <$> getEnvDefault "ENV" "development"
let config = Config env port
runSettings (setPort port $ settings env)
. middlewares env =<< app config
where
env' "development" = Development
env' _ = Production
settings :: Env -> Settings
settings Development = defaultSettings
settings Production =
setFdCacheDuration 10 .
setFileInfoCacheDuration 10 $
settings Development
middlewares :: Env -> Middleware
middlewares Development = logStdoutDev
middlewares Production = logStdout . prometheus def
app :: Config -> IO Application
app _ = scottyApp $ do
get "/" $ do
html =<< render "index.html" []
render :: FilePath -> [Pair] -> ActionM TL.Text
-- Lucid
-- render _ _ = pure $ renderText $ doctypehtml_ "Cool"
-- Mustache
-- render template value = do
-- r <- liftIO $ automaticCompile ["./templates"] template
-- pure $ case r of
-- Left err -> TL.pack $ show err
-- Right tmpl -> TL.fromStrict $ substitute tmpl (object value)
-- EDE
render template value = do
r <- liftIO $ eitherParseFile ("./templates/" <> template)
pure $ case r of
Left err -> TL.pack $ show err
Right tmpl -> either TL.pack id $
eitherRenderWith filters tmpl (fromPairs value)
where
filters = fromList []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment