2014-11-03 41 views
2

我正在通過blaze-html教程開展工作。我只想要一個簡單的Hello World頁面。如何從火焰中獲取html - 打印到文件

{-# LANGUAGE OverloadedStrings #-} 

import Control.Monad (forM_) 
import Text.Blaze.Html5 
import Text.Blaze.Html5.Attributes 
import qualified Text.Blaze.Html5 as H 
import qualified Text.Blaze.Html5.Attributes as A 

import Text.Blaze.Html.Renderer.Text 

notes :: Html 

notes = docTypeHtml $ do 
    H.head $ do 
     H.title "John´ s Page" 
    body $ do 
     p "Hello World!" 

它在哪裏?我如何獲得我的HTML?我可以將它打印到終端或文件嗎?那將是一個很好的開始。

<html> 
<head><title>John's Page</title></head> 
<body><p>Hello World!</p></body> 
</html> 

而且所有的導入語句真的有必要嗎?我只是想讓它工作。


我嘗試使用renderHTML功能打印,但我只是得到一個錯誤信息:

main = (renderHtml notes) >>= putStrLn 
notes.hs:21:9: 
    Couldn't match expected type `IO String' 
       with actual type `Data.Text.Internal.Lazy.Text' 
    In the return type of a call of `renderHtml' 
    In the first argument of `(>>=)', namely `(renderHtml notes)' 
    In the expression: (renderHtml notes) >>= putStrLn 

回答

3

的「renderHtml」不裹在一個單子,所以你不需要結果使用>> =

剛打印出來的結果是:

main = putStrLn $ show $ renderHtml notes 

結果是:

"<!DOCTYPE HTML>\n<html><head><title>John&#39; s 
    Page</title></head><body><p>Hello World!</p></body></html>" 

一般來說,開始用這樣的錯誤的地方是將文件加載到GHCI,看看類型是什麼。下面是我使用的這個問題會議:

*Main> :t notes 
notes :: Html 
*Main> :t renderHtml notes 
renderHtml notes :: Data.Text.Internal.Lazy.Text 

你可以看到,renderHtml的輸出指出僅僅是文本的一個實例。 Text有一個Show實例,所以我們可以調用「putStrLn $ show $ renderHtml notes」來獲得所需的輸出。

但是,使用Data.Text。[Lazy。] IO包在使用Text時執行IO通常會更好。請注意「TIO」的導入以及下面代碼中的最後一行:

{-# LANGUAGE OverloadedStrings #-} 

import Control.Monad (forM_) 
import Text.Blaze.Html5 
import Text.Blaze.Html5.Attributes 
import qualified Text.Blaze.Html5 as H 
import qualified Text.Blaze.Html5.Attributes as A 

import Text.Blaze.Html.Renderer.Text 
import qualified Data.Text.Lazy.IO as TIO 

notes :: Html 

notes = docTypeHtml $ do 
    H.head $ do 
     H.title "John' s Page" 
    body $ do 
     p "Hello World!" 

--main = putStrLn $ show $ renderHtml notes 
main = TIO.putStr $ renderHtml notes