我在使用{%ifequal s1“某些文本”%}时遇到问题,以便在Django模板中比较字符串和扩展字符。当字符串s1包含ascii字符> 127时,我在模板渲染中获得异常。我究竟做错了什么?我在数据,模板和Python代码的其他应用程序中使用UTF-8编码,没有任何问题。
views.py
def test(request):
return render_to_response("test.html", {
"s1": "dados",
"s2": "aprovação",
}
)
的test.html
s1={{s1}}<br>
s2={{s2}}<br>
{% ifequal s1 "dados" %}
s1="dados" is true
{% endifequal %}
{% ifequal s1 "aprovação" %}
s1="aprovação" is true
{% endifequal %}
{% comment %}
The following two comparions cause the following exception:
Caught an exception while rendering: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)
{% ifequal s2 "dados" %}
s2="dados" is true
{% endifequal %}
{% ifequal s2 "aprovação" %}
s2="aprovação" is true
{% endifequal %}
{% endcomment %}
{% ifequal s2 u"dados" %}
s2="dados" is true
{% endifequal %}
{% comment %}
The following comparison causes the following exception:
Caught an exception while rendering: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128)
{% ifequal s2 u"aprovação" %}
s2="aprovação" is true
{% endifequal %}
{% endcomment %}
输出
s1=dados
s2=aprovação
s1="dados" is true
答案 0 :(得分:8)
有时候没有什么能比别向别人描述问题来帮助你解决问题。 :)我应该像这样将Python字符串标记为Unicode,现在一切正常:
def test(request):
return render_to_response("test.html", {
"s1": u"dados",
"s2": u"aprovação",
}
)