views:

1185

answers:

1

I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the rest of application in both the data, templates and Python code without any problems.

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 %}

Output

s1=dados
s2=aprovação
s1="dados" is true
+8  A: 

Sometimes there's nothing like describing a problem to someone else to help you solve it. :) I should have marked the Python strings as Unicode like this and everything works now:

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