Django模板上的Unicode字符串显示
我正在使用django v1.5.*,我将渲染一个名为"foobar"的变量,该变量是json obj,包括unicode字符串.
I am using django v1.5.*, I am going to render the a variable named "foobar" which is a json obj and including unicode string.
def home( request ):
import json
foo = {"name": u"赞我们一下"}
bar = json.dumps( foo )
return render_to_response( 'myapp/home.html',
{ "foobar": bar, },
context_instance=RequestContext(request)
)
在我的模板中,我用javascript编码json obj,然后追加到div,它可以显示预期的字符串:
And in my template, I encode the json obj in javascript and then append to the div, it can display the expected string:
foobar=JSON.encode('{{foobar|safe}}');
$("#foobar").html(foobar.name);`
然后我可以在网页上获取赞一下我们
.
但是我发现如果直接使用变量:
then I can get the 赞一下我们
on my web page.
But I found that if I use the variable directly:
<div id="foobar">{{ foobar }}</div>
它将unicode字符串显示为字节字符串:{ "name":"\u8d5e\u4e00\u4e0b\u6211\u4eec" }
即使我使用{{foobar|safe}}
,也没有任何改变.
it will display the unicode string as byte string:{ "name":"\u8d5e\u4e00\u4e0b\u6211\u4eec" }
Even if I using the {{foobar|safe}}
then nothing change.
现在,我想问为什么会发生这种情况,或者我有什么毛病?如果我想直接将变量用作{{ foobar }}
怎么办?
Now, I want to ask why this happend or is anything wrong of me? What should I do if I do want to using the variable directly as {{ foobar }}
?
bar = json.dumps(foo, ensure_ascii=False)
将导致bar
是unicode
对象;没有 ensure_ascii = False ,bar
是str
.
bar = json.dumps(foo, ensure_ascii=False)
will result in bar
being a unicode
object; without ensure_ascii=False, bar
is a str
.
Django的 smart_text 方法也可能有用进行转化.
Django's smart_text method might also be useful for conversions.