使用lookupSession获取会话值

时间:2013-11-14 05:14:43

标签: haskell yesod

我尝试将一个会话值放在一个变量中,以便在我的.hamlet中显示它,但它没有focntion!

 getEtatR :: Handler Html
 getEtatR = do
     mSessionValue <- lookupSession "myKey"
     let myValue = mSessionValue :: Maybe Text
     defaultLayout $ do
         aDomId <- newIdent
         setTitle "mon titre"
         $(widgetFile "etatWidget")

我需要#{myValue}将它放在我的etat.hamlet

2 个答案:

答案 0 :(得分:1)

问题是myValue的类型,即Maybe Text。为了使变量显示在模板中,它必须是Text.Blaze.ToMarkup的实例....所以Text,String或Int都可以工作,但“Maybe a”不会。

有很多方法可以将“Maybe Text”转换为ToMarkup。如果您确定Maybe可能不会是“Nothing”,只需使用fromJust(从Data.Maybe导入)即可剥离....但要注意,如果它确实出现了Nothing程序将崩溃。类似地,您可以使用case语句填写Nothing案例,例如

myVariable = case mSessionValue of
                         Just x -> x
                         Nothing -> "<No session value>"

您还可以使用show。

将mSessionValue转换为字符串进行快速检查

以下为我工作....

getEtatR :: Handler Html
getEtatR = do
     mSessionValue <- lookupSession "myKey"
     let myValue = show mSessionValue
     defaultLayout $ do
         aDomId <- newIdent
         setTitle "mon titre"
         $(widgetFile "etatWidget")

使用etatWidget.hamlet

<h1>#{myValue}

答案 1 :(得分:0)

如果您只想显示该值并将其从Maybe中删除,您可以直接在小村内执行此操作

$maybe val <- mSessionValue
   <p>#{val}
$nothing
    <p>No Value Set