如何将引导程序添加到YesodForm

时间:2016-06-04 14:51:23

标签: haskell yesod yesod-forms

我需要帮助才能将BootStrap添加到我的YesodForm项目中。伙计们,你能帮助我吗?

这就是我的代码。我只想添加BootStrap样式添加到我的html组件 我已经阅读了aloot教程,但是很复杂,我是Haskell的新手。对于那个简单的项目,我需要一个简单的事情。 Thank.s

{-# LANGUAGE OverloadedStrings, TypeFamilies, QuasiQuotes,
             TemplateHaskell, GADTs, FlexibleInstances,
             MultiParamTypeClasses, DeriveDataTypeable,
             GeneralizedNewtypeDeriving, ViewPatterns, EmptyDataDecls #-}
import Yesod
import Database.Persist.Postgresql
import Data.Text
import Text.Lucius
import Control.Monad.Logger (runStdoutLoggingT)

data Pagina = Pagina{connPool :: ConnectionPool}

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Animals json
   nome Text
   idade Int
   deriving Show

Users json
   nome Text
   login Text
   senha Text
   deriving Show
|]

mkYesod "Pagina" [parseRoutes|
/ HomeR GET
/animal/cadastro AnimalR GET POST
/animal/checar/#AnimalsId ChecarAnimalR GET
/erro ErroR GET

/login LoginR GET POST
/usuario UsuarioR GET POST
/perfil/#UsersId PerfilR GET
/admin AdminR GET
/logout LogoutR GET
|]

instance Yesod Pagina where
    authRoute _ = Just LoginR

    isAuthorized LoginR _ = return Authorized
    isAuthorized ErroR _ = return Authorized
    isAuthorized HomeR _ = return Authorized
    isAuthorized UsuarioR _ = return Authorized
    isAuthorized AdminR _ = isAdmin
    isAuthorized _ _ = isUser

isUser = do
    mu <- lookupSession "_ID"
    return $ case mu of
        Nothing -> AuthenticationRequired
        Just _ -> Authorized

isAdmin = do
    mu <- lookupSession "_ID"
    return $ case mu of
        Nothing -> AuthenticationRequired
        Just "admin" -> Authorized 
        Just _ -> Unauthorized "Acesso Restrito para Administrador"

instance YesodPersist Pagina where
   type YesodPersistBackend Pagina = SqlBackend
   runDB f = do
       master <- getYesod
       let pool = connPool master
       runSqlPool f pool

type Form a = Html -> MForm Handler (FormResult a, Widget)

instance RenderMessage Pagina FormMessage where
    renderMessage _ _ = defaultFormMessage
------------------------

formAnimal :: Form Animals
formAnimal = renderDivs $ Animals <$>
           areq textField "Nome: " Nothing <*>
           areq intField "Idade: " Nothing

formUser :: Form Users
formUser = renderDivs $ Users <$>
           areq textField "Nome: " Nothing <*>
           areq textField "Login: " Nothing <*>
           areq passwordField "Password: " Nothing

formLogin :: Form (Text,Text)
formLogin = renderDivs $ (,) <$>
           areq textField "Login: " Nothing <*>
           areq passwordField "Senha: " Nothing           

getAnimalR :: Handler Html
getAnimalR = do
           (widget, enctype) <- generateFormPost formAnimal
           defaultLayout $ do 
           toWidget [cassius|
               label
                   color:blue;
           |]
           [whamlet|
                 <form .form-horizontal method=post enctype=#{enctype} action=@{AnimalR}>
                     ^{widget}
                     <input type="submit" value="Cadastrar Animal">
           |]

getPerfilR :: UsersId -> Handler Html
getPerfilR uid = do
      user <- runDB $ get404 uid
      defaultLayout $ do
          toWidget $ $(luciusFile "templates/perfil.lucius")
          $(whamletFile "templates/perfil.hamlet")

getUsuarioR :: Handler Html
getUsuarioR = do
           (widget, enctype) <- generateFormPost formUser
           defaultLayout [whamlet|
                 <form method=post enctype=#{enctype} action=@{UsuarioR}>
                     ^{widget}
                     <input type="submit" value="Enviar">
           |]

postAnimalR :: Handler Html
postAnimalR = do
           ((result, _), _) <- runFormPost formAnimal
           case result of 
               FormSuccess anim -> (runDB $ insert anim) >>= \piid -> redirect (ChecarAnimalR piid)
               _ -> redirect ErroR

postUsuarioR :: Handler Html
postUsuarioR = do
           ((result, _), _) <- runFormPost formUser
           case result of 
               FormSuccess user -> (runDB $ insert user) >>= \piid -> redirect (PerfilR piid)
               _ -> redirect ErroR

getHomeR :: Handler Html
getHomeR = defaultLayout [whamlet|Hello World!|]

addStyle :: Widget
addStyle = addStylesheetRemote "http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/css/bootstrap-combined.min.css"

getAdminR :: Handler Html
getAdminR = defaultLayout [whamlet|
    <b><h1><font size="11"> Bem vindo ao Painel Administrativo</font></h1></b>
|]

getLoginR :: Handler Html
getLoginR = do
           (widget, enctype) <- generateFormPost formLogin
           defaultLayout [whamlet|
                 <form method=post enctype=#{enctype} action=@{LoginR}>
                     ^{widget}
                     <input type="submit" value="Login">
           |]

postLoginR :: Handler Html
postLoginR = do
           ((result, _), _) <- runFormPost formLogin
           case result of 
               FormSuccess ("admin","eitapleuga") -> setSession "_ID" "admin" >> redirect AdminR
               FormSuccess (login,senha) -> do 
                   user <- runDB $ selectFirst [UsersLogin ==. login, UsersSenha ==. senha] []
                   case user of
                       Nothing -> redirect LoginR
                       Just (Entity pid u) -> setSession "_ID" (pack $ show $ fromSqlKey pid) >> redirect (PerfilR pid)

getChecarAnimalR :: AnimalsId -> Handler Html
getChecarAnimalR pid = do
    animal <- runDB $ get404 pid
    defaultLayout  [whamlet|
    <font size="10">Perfil do Pet</font><br>
        <p><b> Nome do Pet:</b>  #{animalsNome animal}  
        <p><b> Idade do Pet:</b> #{show $ animalsIdade animal} Anos
    |]

getErroR :: Handler Html
getErroR = defaultLayout [whamlet|
    <h1>Falha no Cadastro !</h1>
|]

getLogoutR :: Handler Html
getLogoutR = do
     deleteSession "_ID"
     defaultLayout [whamlet| 
         <h1> <b>Logout</b> efetuado com sucesso! </h1>
     |]

connStr = "dbname=d4673as0stmsm7 host=ec2-54-221-225-242.compute-1.amazonaws.com user=nzjfptmglfomng password=fyYms4A9T8gkP4_Go8GswcfIiE port=5432"

主:: IO() main = runStdoutLoggingT $ withPostgresqlPool connStr 10 $ \ pool - &gt; liftIO $ do        runSqlPersistMPool(runMigration migrateAll)池        经编8080(Pagina池)

2 个答案:

答案 0 :(得分:1)

您可以将其添加到Handler功能中,如下所示:

getUsuarioR :: Handler Html
getUsuarioR = do
       (widget, enctype) <- generateFormPost formUser
        defaultLayout $ do
           addStylesheetRemote "http://remote-bootstrap-path.css"
           [whamlet|
                 <form method=post enctype=#{enctype} action=@{UsuarioR}>
                     ^{widget}
                     <input type="submit" value="Enviar">
           |]

此外,如果您是Haskell的新手,我建议您在潜入Yesod之前先学习一些最小的Haskell。

答案 1 :(得分:0)

特别是对于第一个项目,我建议使用脚手架网站。您可以按照Yesod主页上的快速入门指南获取它。您不仅可以获得合理的默认设置,而且还具有已集成的bootstrap css。

缺点当然是脚手架会向你抛出许多你可能不想要或不同意的东西和意见。但即使你不喜欢脚手架,你也可以将它们放在一个单独的文件夹中,只需从中获取灵感并将其中的一部分合并到你自己的网站中 - 比如引导程序或jquery的集成。

接下来需要做的是将适当的类添加到html元素中。根据上下文,有两种方法可以做到这一点。在你自己的小部件中,你可以像添加任何其他类一样添加它们(在它前面有一个点)。如果使用生成的代码(例如表单或yesod-table),则通常可以在不同的呈现函数之间进行选择。例如,您可以使用 renderTable 渲染功能在两列中渲染表单。但是几乎总会有另一个名称为 renderBootstrap 的函数,它会将内容呈现为带有引导类的普通div。

总而言之,Yesod与bootstrap非常完美地集成在一起。在我个人看来,甚至太多了。但在你的情况下,它应该在初始设置混乱后使你的任务相对容易。