Webanwendung mit FastCGI und Haskell
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

55 lignes
1.6KB

  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# OPTIONS -Wall #-}
  3. module Template (
  4. initTemplates, render, Context
  5. ) where
  6. import Control.Monad.State
  7. import Data.ByteString.Char8 (pack)
  8. import Data.Binary.Builder
  9. import Control.Lens (set)
  10. import Data.ByteString.Lazy (toStrict)
  11. import qualified Data.Text as T (pack, unpack)
  12. import Data.Text.Encoding
  13. import Heist
  14. import Heist.Interpreted
  15. import AppMonad
  16. import Database
  17. type TemplateName = String
  18. type Context = [(String, String)]
  19. basePath :: FilePath
  20. basePath = "/home/christian/work/haskell/haskweb/"
  21. heistConfig :: HeistConfig App
  22. heistConfig =
  23. (set hcNamespace "") $
  24. (set hcLoadTimeSplices defaultLoadTimeSplices) $
  25. (set hcTemplateLocations [loadTemplates $ basePath ++ "templates"]) $
  26. emptyHeistConfig
  27. initTemplates :: App ()
  28. initTemplates = do
  29. heistState <- liftIO $ either (error . concat) id
  30. <$> initHeist heistConfig
  31. modify $ setHeistState heistState
  32. render :: TemplateName -> Context -> App String
  33. render tpl oldContext = do
  34. hs <- maybe (error "Template engine not initialized!") id <$> gets heist
  35. loginStatus <- isLoggedIn
  36. let context = ("login_path", if loginStatus then "/logout" else "/login") :
  37. ("login_name", if loginStatus then "Abmelden" else "Anmelden") :
  38. oldContext
  39. hs' = foldr (\(k, v) h -> bindString (T.pack k) (T.pack v) h) hs context
  40. mayBuilder <- renderTemplate hs' (pack tpl)
  41. case mayBuilder of
  42. Just (builder, _) ->
  43. return . T.unpack . decodeUtf8 . toStrict . toLazyByteString $ builder
  44. Nothing -> return $ "Could not load template!"