代码之家  ›  专栏  ›  技术社区  ›  Jonno_FTW

使用Text.XHtml嵌套

  •  3
  • Jonno_FTW  · 技术社区  · 16 年前

    下面的代码使用 Text.XHtml.Strict

    module Main where
    
    import Text.XHtml.Strict
    import Text.Printf
    
    
    page :: Html
    page = pHeader +++ pTop +++ pBody +++ pFooter
    
    pHeader :: Html
    pHeader = header << thetitle << "Page title" 
    
    pTop :: Html
    pTop = (dC "header") << (dI "title") 
    
    pFooter :: Html
    pFooter = (dC "footer") << (dI "foottext")
    
    pBody :: Html
    pBody = body << (dC "main") << (dI "window") << (dI "content")
    
    dC :: String -> Html
    dC x = (thediv noHtml)! [theclass x]
    
    dI :: String -> Html
    dI x = (thediv noHtml) ! [identifier x]
    
    main :: IO ()
    main = do
        printf $ prettyHtml $ page
    

    功能 dC 和 dI 应分别使用类或id将。在解释器中,这些函数在连接时工作良好,如:

     printf $ prettyHtmlFragment $ dC "1" +++ dC "2"
    <div class="1">
    </div>
    <div class="2">
    </div>
    

    但当我尝试使用 << 而不是 +++ ,我得到一个错误:

    <interactive>:1:28:
        Couldn't match expected type `Html -> b'
               against inferred type `Html'
    

    2 回复  |  直到 8 年前
        1
  •  2
  •   duplode    8 年前

    只需取出 nohtml 零件,并更改签名:

    dC :: String -> Html -> Html
    dC x = thediv ! [theclass x]
    
    dI :: String -> Html -> Html
    dI x = thediv ! [identifier x]
    

    ! 运算符不仅可以将属性添加到 Html Html thediv 函数是 并将其包装在 <div> 元素。申请 ! Html 并包装了一个 <div class="…"> (或 id="…" )围绕着它。

    > :type thediv
    thediv :: Html -> Html
    
    > let dC c = thediv ! [theclass c]
    > let dI i = thediv ! [identifier i]
    
    > :type dC
    dC :: String -> Html -> Html
    > :type dI
    dI :: String -> Html -> Html
    
    > putStr $ prettyHtmlFragment $ body << dC "main" << dI "window" << dI "content" << "Hi"
    <body>
       <div class="main">
          <div id="window">
             <div id="content">
                Hi
             </div>
          </div>
       </div>
    </body>
    

    请注意,您不需要额外的括号。

        2
  •  1
  •   ja.    16 年前

    dC和cI无法嵌套,因为它们被定义为空。您需要留下一个嵌套工件将进入的孔。孔通过参数化表示:

    dC classx child = (thediv child)! [theclass classx] 
    dI x y = (thediv y) ! [identifier x] 
    

    同样,对于身体:

    pBody x = body << (dC "main") << (dI "window") << (dI "content" x) 
    
    推荐文章