简体   繁体   English

模板标签值中的Django非ASCII字符

[英]Django non-ASCII chars in template tags values

I'm writing a custom Django template tag for a french application. 我正在为法语应用程序编写自定义Django模板标签 My template tag takes a parameter which is a string: 我的模板标签接受一个字符串参数:

{% mytag "Hello" %}

Is works perfect, but fails when trying to put some non-ASCII chars in the value. 是完美的作品,但是在尝试将一些非ASCII字符放入值时失败。

How would you get this thing work: 您如何使这件事起作用:

{% mytag "Êtes-vous à Paris ?" %}

I got this error: 我收到此错误:

'ascii' codec can't encode character u'\\xca' in position 0: ordinal not in range(128) 'ascii'编解码器无法在位置0编码字符u'\\ xca':序数不在范围内(128)

Unicode error hint Unicode错误提示

The string that could not be encoded/decoded was: Êtes-v 无法编码/解码的字符串是:Êtes-v

Thanks very much in advance! 首先十分感谢!

EDIT: Python version is 2.7 . 编辑:Python版本是2.7 Here is the code of the tag: 这是标记的代码:

@register.simple_tag(takes_context=True)
def mytag(context, my_var):
    return "Here it is: {my_var}".format(my_var=my_var)

Try replacing 尝试更换

return "Here it is: {my_var}".format(my_var=my_var)

by 通过

return u"Here it is: {my_var}".format(my_var=my_var)

In Python 2.7, "Here it is: {my_var}" is a str object, an encoded string, my_var is a unicode object, a decoded string, when formatting, Python will try to encode my_var so it matches the type of the formatting string. 在Python 2.7中, "Here it is: {my_var}"是一个str对象,一个编码字符串, my_var是一个unicode对象,一个解码字符串,在格式化时,Python将尝试对my_var进行编码,以便它与格式化字符串的类型匹配。 It does so using the ascii codec by default which does not support special characters. 这样做是默认情况下使用不支持特殊字符的ascii编解码器。

Adding the u before the formatting string makes it a unicode string, no encoding will take place during formatting. 在格式化字符串之前添加u使其成为unicode字符串,格式化期间不会进行任何编码。

Since it looks like you might speak French, I advise you to read this article which is a great guide to encoding in Python. 由于您似乎会说法语,因此建议您阅读这篇文章 ,这是使用Python编码的绝佳指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM