0

你好呀。

这是我试图使工作的代码:

getGameR :: Handler Html
getGameR = do
    sess <- getSession
    defaultLayout $ do
        setTitle "Game"
        $(widgetFile "hamletFile")
    where
        person = read $ fromJust $ Map.lookup "person" sess :: Person

data Person = Person
    {
        name :: Text
    }
    deriving (Show, Read)


错误如下:

Handler/MyHandler.hs:87:56: Not in scope: `sess'


我正在尝试做的是从 Yesod Session 中提取数据(Person 类型的数据)并将其存储在“person”中,以便能够在 hamlet 文件中使用它。

有没有办法绕过这个错误?

如果不可能,你能建议另一种方法吗?

提前致谢。

4

2 回答 2

4

sessdo块本地的,因此它不在person定义的范围内。就该错误而言,letdo块内使用就足够了:

getGameR :: Handler Html
getGameR = do
    sess <- getSession
    let person = read $ fromJust $ Map.lookup "person" sess :: Person
    defaultLayout $ do
        setTitle "Game"
        $(widgetFile "hamletFile")
于 2013-10-17T20:12:59.083 回答
1

如果您只想查找单个值,请考虑lookupSession改用。此外,fromJust如果密钥不在会话中,则抛出异常,您可以使用fromMaybe

getGameR :: Handler Html
getGameR = do
    mbPersonName <- lookupSession "person"
    let defaultPerson = Person "anonymous"
    let person = fromMaybe defaultPerson (readMaybe .unpack =<< mbPersonName) :: Person
    defaultLayout $ do
        setTitle "Game"
        $(widgetFile "hamletFile")

这是我处理会话的助手:

import Text.Read (readMaybe)
import Data.Maybe (fromMaybe)

readSession :: Read a => Text -> Handler (Maybe a)
readSession name = do
    textValue <- lookupSession name
    return (readMaybe . unpack =<< textValue)

readSessionDef :: Read a => a -> Text -> Handler a
readSessionDef def name =  do
    mbValue <- readSession name
    return $ fromMaybe def mbValue

readSession读取任何可以读取的内容并返回一个Maybe. readSessionDef如果会话中不存在此类键,则返回默认值:

getGameR :: Handler Html
getGameR = do
    person <- readSessionDef (Person "anonymous") "person"
    defaultLayout $ do
        setTitle "Game"
        $(widgetFile "hamletFile")
于 2013-10-18T03:08:12.117 回答