我正在使用django中的format_html(..)函数。当我使用像重音符这样的特殊字符时,它会失败。有没有办法将format_html(..)与特殊字符一起使用?
我找到的解决方案是:
format_html('<label>{0}</label>', smart_text(classes).encode('ascii', 'ignore'))
但它只删除了特殊字符。
答案 0 :(得分:2)
正确的解决方案是像Django一样from __future__ import unicode_literals
,或者.format
上的unicode
而不是str
。
答案 1 :(得分:1)
尝试
format_html(u'<label>{0}</label>', smart_text(classes))
我相信这就是Krzysztof Szularz在他的第二个建议中的意思。
答案 2 :(得分:1)
如果要传递任何unicode参数,则格式字符串必须是unicode。如果格式字符串是ASCII,则所有参数也必须是ASCII。
这是str.format()
使用的format_html()
方法的要求。
所以在字符串前面添加u
以使其成为unicode字符串:
u'<label>{0}</label>'
在您的代码中,它将是:
format_html(u'<label>{0}</label>', smart_text(classes))