0
import Data.String.Conversions
import Data.Maybe (isJust)
import qualified Heist
import qualified Heist.Interpreted as I
import qualified Heist.Compiled as HeistCom
import Heist.Internal.Types
import qualified Text.XmlHtml as X
import Data.List (sortBy)
import Data.Map.Syntax
import Data.ByteString.Builder (toLazyByteString)

renderTemplate :: String -> (HeistState IO -> HeistState IO) -> ActionM ()
renderTemplate fileName hsBinding = do
  let emptyI = return () :: MapSyntax Text (I.Splice IO)
  let emptyC = return () :: MapSyntax Text (HeistCom.Splice IO)
  let emptyA = return () :: MapSyntax Text (AttrSplice IO)
  let spliceConfig = SpliceConfig emptyI emptyI emptyC emptyA [] (\_ -> False):: SpliceConfig IO
  heist <- lift $ Heist.initHeist (HeistConfig spliceConfig "" True)
  case heist of
    Right heist' -> do
      rendered <- lift $ I.renderTemplate (hsBinding heist') $ convertString fileName
      case (rendered) of
        Just (builder, _) -> do
          lift $ print $ toLazyByteString builder
        Nothing -> error "heist error"
    Left a -> error . convertString $ show a

我这样调用函数:

renderTemplate "templates/compareForm"  $ I.bindSplice "test" $ I.textSplice "abcxyz"

我猜这与配置有关。我还没有彻底考虑过上面的配置。

不幸的是,上面只是产生“抢劫错误”的错误(倒数第二行)。所以我的问题是为什么?我的下一步将是调查该Heist.Interpreted.renderTemplate功能。

4

1 回答 1

1

终于想通了...我需要指定一个模板位置...

renderTemplate :: String -> (HeistState IO -> HeistState IO) -> ActionM ()
renderTemplate fileName hsBinding = do
  let emptyI = return () :: MapSyntax Text (I.Splice IO)
  let emptyC = return () :: MapSyntax Text (HeistCom.Splice IO)
  let emptyA = return () :: MapSyntax Text (AttrSplice IO)
  let templateLocations = [Heist.loadTemplates "templates/"]
  let spliceConfig = SpliceConfig emptyI emptyI emptyC emptyA templateLocations (\_ -> False):: SpliceConfig IO
  heist <- lift $ Heist.initHeist (HeistConfig spliceConfig "" True)
  case heist of
    Right heist' -> do
      rendered <- lift $ I.renderTemplate (hsBinding heist') $ convertString fileName
      case (rendered) of
        Just (builder, _) -> do
          html . convertString $ toLazyByteString builder
        Nothing -> error "heist error"
    Left a -> error . convertString $ show a

并且渲染路径不应指定目录:

renderTemplate "compareForm"  $ I.bindSplice "test" $ I.textSplice "abcxyz"

以上可能不适用于已编译的模板,可能需​​要修改这一行(可能是(\_ -> False)let spliceConfig = SpliceConfig emptyI emptyI emptyC emptyA templateLocations (\_ -> False):: SpliceConfig IO

上述内容可能会对性能产生影响,请参阅https://github.com/snapframework/heist/issues/102

于 2017-02-08T14:01:51.540 回答