5

我在使用 {% ifequal s1 "some text" %} 将字符串与 Django 模板中的扩展字符进行比较时遇到问题。当字符串 s1 包含 >127 的 ascii 字符时,我在模板渲染中遇到异常。我究竟做错了什么?我在数据、模板和 Python 代码的其余应用程序中使用 UTF-8 编码,没有任何问题。

视图.py

def test(request):
    return render_to_response("test.html", {
                                            "s1": "dados",
                                            "s2": "aprovação",
                                            }
                              )

测试.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 
4

1 回答 1

8

有时没有什么比向其他人描述问题来帮助您解决问题更重要的了。:) 我应该像这样将 Python 字符串标记为 Unicode,现在一切正常:

def test(request):
    return render_to_response("test.html", {
                                            "s1": u"dados",
                                            "s2": u"aprovação",
                                            }
                              )
于 2009-01-27T17:29:17.833 回答