【问题标题】:How to compose widgets with blaze code in Yesod?如何在 Yesod 中使用 blaze 代码编写小部件?
【发布时间】:2016-08-10 14:17:39
【问题描述】:

我正在尝试编写一个没有任何小村庄部分的 yesod 应用程序。我的问题是关于表单的:我可以使用 Applicative 生成​​表单,但我不能直接在我的 blaze 代码中使用它。

这里是一个小村庄版本的例子:

-- actual form example
userForm :: Form User
userForm = renderDivs $ User
  <$> areq textField "Login" Nothing
-- usage example
getPageR :: Handler Html
getPageR = do
  ((_, widget), enctype') <- runFormGet userForm
  defaultLayout [whamlet|
                 <form method=post action=@{PageR} enctype=#{enctype'}>
                 ^{widget} -- This widget include.
                 <button>Submit|]

但是如果没有 hamlet,我怎么能重写它呢?我现在的代码是这样的:

getPageR = do
  ((_, widget), enctype') <- runFormGet userForm
  defaultLayout $ do
    toWidgetBody $ \render -> do
      H.div ! A.id "form" $ do
        H.form ! A.method "post" ! A.action (action' render) ! A.enctype (enct' enctype) $ ""
        -- widget include?
        H.button "Submit!"
   where
     action' = \render -> toValue $! render (PageR) []
     enct'   = toValue . renderHtml . toHtml

很明显,blaze代码的类型是Html,而userForm类型是Widget,所以无法连接。我只能在toWidgetBody 函数之后添加小部件,但随后表单将是所有内容。有没有办法在没有 hamlet ^{widget} 构造的情况下在 blaze 组合器中包含表单(通过将其渲染为 Html,也许?)?

【问题讨论】:

    标签: haskell yesod


    【解决方案1】:

    使用widgetToPageContent 函数。

    然后,您可以通过调用pageBody 并应用render 函数来访问Html

    getPageR :: Handler Html -- same as: HandlerT App IO Html
    getPageR = do
      ((_, widget), enctype') <- runFormGet sampleForm
      content <- widgetToPageContent widget
      defaultLayout $ do
        toWidgetBody $ \render -> do
          H.div ! A.id "form" $ do
            H.form ! A.method "post" ! A.action (action' render)
                                     ! A.enctype (enct' enctype') $ ""
            pageBody content render
            H.button "Submit!"
       where
         action' = \render -> toValue $! render (PageR) []
         enct'   = toValue . renderHtml . toHtml
         (!) = (H.!)
         toValue = H.toValue
    

    【讨论】:

    • 如果我想使用一元形式而不是应用形式,是否也可以将 FieldView 扩展到 Html 以在小部件定义中使用它?
    • 请使用适当的代码示例为此打开一个新问题 - 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多