【问题标题】:How to use Pandoc's writeHtmlString when using IO String for template使用 IO String 为模板时如何使用 Pandoc 的 writeHtmlString
【发布时间】:2013-06-12 00:06:18
【问题描述】:

我在将 markdown 文件转换为 html 文件并尝试让 IO 与纯系统配合使用时正在读取模板文件。

template :: IO String
template = readFile "/File/Path/template.html"

siteOptions :: WriterOptions
siteOptions = def { writerStandalone = True, writerTemplate = template }

convertMdtoHtml :: FilePath -> IO () 
convertMdtoHtml file = do
  contents <- readFile file 
  let pandoc = readMarkdown def contents
  let html = writeHtmlString siteOptions pandoc
  writeFile (file ++ ".html") html

这是我尝试使用的 writeHtmlString 的文档http://hackage.haskell.org/packages/archive/pandoc/1.11.1/doc/html/Text-Pandoc-Writers-HTML.html

我在尝试运行时遇到的错误是

 Couldn't match expected type `String' with actual type `IO String'

有没有办法在haskell中做到这一点,或者我需要将模板文件作为字符串已经存在于代码中。

谢谢

【问题讨论】:

    标签: haskell pandoc


    【解决方案1】:

    使template成为siteOptions的参数:

    siteOptions :: String -> WriterOptions
    siteOptions template = def { writerStandalone = True, writerTemplate = template }
    
    convertMdtoHtml :: FilePath -> IO () 
    convertMdtoHtml file = do
      ...
      template <- readFile "/File/Path/template.html"
      let html = writeHtmlString (siteOptions template) pandoc
    

    template :: IO String 是一个IO 操作 - 一段不纯(副作用)代码,执行时将产生String 类型的结果。这就是为什么您不能在需要 String 的上下文中使用它的原因。

    如果您想在编译时将"/File/Path/template.html" 的内容包含在您的程序中,请考虑使用Template Haskell

    > :set -XTemplateHaskell
    > import Language.Haskell.TH.Syntax
    > import Language.Haskell.TH.Lib
    > let str = $(stringE =<< (runIO (readFile "/path/to/foo")))
    > str
    "bar\n"
    > :t str
    str :: [Char]
    

    【讨论】:

    • 感谢 Mikhail 如此迅速地回答。我认为是在细节中寻找太多而忘记了整体情况。感谢您提供有关 TemplateHaskell 的更多详细信息,我认为这样的事情对于我正在尝试做的事情来说太过分了。
    猜你喜欢
    • 2022-01-08
    • 2021-07-22
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2021-08-07
    • 2013-06-17
    相关资源
    最近更新 更多