【问题标题】:Haskell Happstack, can I use a string with html tags as response?Haskell Happstack,我可以使用带有 html 标签的字符串作为响应吗?
【发布时间】:2015-04-20 00:34:33
【问题描述】:
    module Main where

    import Happstack.Lite
    import Text.Html

    main :: IO ()
    main = serve Nothing $ msum [
              nullDir >> ok homePage
            , notFound page404  
        ]

    homePage :: Response
    homePage = toResponse $ do
        p (toHtml "hello") +++ 
            strong (toHtml "BOLD")

    page404 :: Response
    page404 = toResponse "<strong>How do I parse the tag STRONG?</strong>"

您好,我是 happstack 的新手。我想知道是否有一种方法可以只显示带有 html 标签的字符串作为响应,而不是使用 html 模板库?

在上面的代码中,page404中的&lt;strong&gt;标签被转义了,所以我得到了“&lt;strong&gt;How do I pase the tag BOLD?&lt;/strong&gt;”作为响应,而一个主页呈现为“如何解析标签BOLD”。

我必须先解析字符串吗?但是如果html字符串很大,那会不会太慢?

提前致谢。

【问题讨论】:

  • 你确定 HTML 被转义了吗?查看ToMessage String instance,看起来响应类型是唯一错误的地方。在这种情况下,您有多种选择:您可以 newtype String 并创建一个单独的实例,但使用不同的内容类型,或者您可以使用不同的组合器。
  • 感谢您的回复。我成功编译并运行了上面的代码。我认为没有类型错误。标签被转义,例如在路由http://localhost:8000/no-such-route
  • 我没有声称有。只是您需要更改响应类型,因为 ToMessage String 实例将其设置为 text/plain 而不是 text/html。
  • 我可以接受你作为答案吗? ; )

标签: haskell happstack


【解决方案1】:

ToMessage String 实例将响应类型设置为 text/plain 而不是 text/html。

您可以为新类型的String 编写自己的实例,该实例本质上是原始实例的副本,但响应类型设置为 text/html,或者使用库中的不同工具来更改响应类型。

此外,您可能应该注意到,在 404 错误上发送 200 HTTP 响应会令人困惑。

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 2011-01-10
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    相关资源
    最近更新 更多