如何用snap和heist显示utf8文本? [英] How to show utf8 text with snap and heist?

查看:109
本文介绍了如何用snap和heist显示utf8文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Snap中使用 writeBS writeText 并且 renderTemplate from heist,但他们都没有支持unicode。

I have used writeBS writeText from Snap and renderTemplate from heist but none of them seems to support unicode.

site :: Snap ()
site = do
    ifTop (writeBS "你好世界") <|>
    route [("test", testSnap)]

testSnap :: Snap ()
testSnap = do
     fromJust $ C.renderTemplate hs "test"

-- test.tpl

你好世界

我期望它为 / / test 路由输出你好世界,但实际上它的输出只是一些乱码。

I expected it to output "你好世界" for the / or /test route, but in fact its output is just some messy code.

推荐答案

这里的问题与writeBS或writeText不同。它是由OverloadedStrings扩展使用的转换。理解ByteString和Text之间的区别也很重要。 ByteString用于原始字节。没有字符或编码的概念。这就是文本的来源。 Data.Text.Encoding 模块具有一组用于使用不同编码在Text和ByteString之间进行转换的函数。对于我来说,以下两种产生相同的输出:

The problem here is not with writeBS or writeText. It's with the conversion used by the OverloadedStrings extension. It is also important to understand the distinction between ByteString and Text. ByteString is for raw bytes. There is no concept of characters or an encoding. That is where Text comes in. The Data.Text.Encoding module has a bunch of functions for converting between Text and ByteString using different encodings. For me, both of the following generate the same output:

writeBS $ encodeUtf8 "你好世界"
writeText "你好世界"

你的代码不工作的原因是你的字符串文字被转换为ByteString由OverloadedStrings扩展,并没有给你你想要的行为。解决的办法是把它当作正确的类型...... Text。

The reason your code didn't work is because your string literal is being converted to ByteString by the OverloadedStrings extension, and it is not giving you the behavior you want. The solution is to treat it as the proper type...Text.

在Heist方面,以下工作适合我:

On the Heist side of things, the following works fine for me:

route [("test", cRender "test")]

实际上,这个在我的浏览器中正确呈现,而前两个则没有。区别在于 cRender 设置了适当的内容类型。

In fact, this one renders correctly in my browser, while the previous two don't. The difference is that cRender sets an appropriate content-type. I found it enlightening to observe the differences using the following snippet.

site = route [ ("/test1", writeBS "你好世界")
             , ("/test2", writeBS $ encodeUtf8 "你好世界")
             , ("/test3", writeText "你好世界")
             , ("/test4", modifyResponse (setContentType "text/html;charset=utf-8") >> writeText "你好世界")
             , ("/testHeist", cRender "test")
             ]

在我的浏览器中,test4和testHeist工作正常。测试2和3给了你正确的行为,但由于缺乏内容类型,浏览器可能无法正确呈现。

In my browser test4 and testHeist work correctly. Tests 2 and 3 give you the correct behavior but might not be rendered properly by browsers because of the lack of content-type.

这篇关于如何用snap和heist显示utf8文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆