【问题标题】:Yesod how to get record from inside hamletYesod如何从小村庄内部获取记录
【发布时间】:2013-11-07 11:53:41
【问题描述】:

问题:在给定 Maybe PersistInt64(可能是 primaryKey)的情况下,我如何从数据库中获取记录
从小村庄内部

假设我有一个主页。
如果有人访问我的主页并已登录。
该人将以其姓名受到欢迎,并可以选择退出。
如果有人访问我的主页但未登录。
系统将要求此人登录。

muid 可能是 PersistInt64
我想在 hamlet 代码中获取用户的记录,因为
如果有人访问未登录的主页将导致错误
如果我们尝试获取没有任何内容而不是 PersistInt64 的记录

所以我只想通过 userId aka (fromJust muid) 获取记录
当 muid 不是什么,并且在 $maybe _ 的代码块中时

getHomeR :: Handler Html
getHomeR = do
    muid <- maybeAuthId
    defaultLayout $ do
        [whamlet|
            <p>Welcome!
        $maybe _ <- muid
            <p>
                $with user <- fromJust (runDB $ get (fromJust muid)) 'does not work'        
                Welcome #{userIdent user}<br>
                <a href=@{AuthR LogoutR}>Logout
        $nothing
            <p>
                <a href=@{AuthR LoginR}>Go to the login page
|]

【问题讨论】:

    标签: database haskell yesod hamlet


    【解决方案1】:

    一种方法是(以下解释):

    getHomeR :: Handler Html
    getHomeR = do
        muid <- maybeAuthId
        m <- case muid of
            Nothing -> return Nothing
            Just i  -> runDB $ get i
    
        defaultLayout $ do
            [whamlet|
                <p>Welcome!
            $maybe user <- m
                <p>        
                    Welcome #{userIdent user}<br>
                    <a href=@{AuthR LogoutR}>Logout
            $nothing
                <p>
                    <a href=@{AuthR LoginR}>Go to the login page
    |]
    

    这样,我们从 m 中创建了一个 Maybe User,并在我们的模板文件中解析它。 注意$maybe user &lt;- m,这(大致)转换为

    case m of
        Just user -> do
            -- Do stuff with user, which is now of type User (and not Maybe User)
        Nothing -> do
            --Do stuff if m was nothing
    

    所以最好不要使用通配符$maybe _ &lt;- muid

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      相关资源
      最近更新 更多