Reputation: 2002
The question: how do i get a record from the dataBase given a Maybe PersistInt64 (maybe primaryKey)
from inside hamlet
let's say i have a homepage.
If a person visit my homepage who is logged in.
The person will be welcomed with his name and has the option to log out.
If a person visit my homepage who is not logged in.
The person will be asked to log in.
muid is a maybe PersistInt64
I want to get the user's record inside the hamlet code because
if someone visit the homepage who is not logged in it will cause a error
if we try to fetch a record with a nothing instead of a PersistInt64
so i only want to fetch a record by the userId aka (fromJust muid)
when muid is not nothing and that's in the code block of $maybe _ <- muid
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
|]
Upvotes: 0
Views: 188
Reputation: 251
One way to do it would be (explanation below):
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
|]
This way, we make a Maybe User out of m, and parse that in our template file.
Notice the $maybe user <- m
, this (roughly) translates to
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
So it's better not to wildcard your $maybe _ <- muid
Upvotes: 3