代码之家  ›  专栏  ›  技术社区  ›  gerdemb

Django模板中的编码问题

  •  5
  • gerdemb  · 技术社区  · 16 年前

    我在使用%ifequal s1“some text”%比较Django模板中的字符串和扩展字符时遇到问题。当字符串s1包含ASCII字符>127时,我会在模板呈现中获得异常。我做错什么了?我在应用程序的其余部分使用UTF-8编码,包括数据、模板和Python代码,没有任何问题。

    VIEW

    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 
    
    1 回复  |  直到 16 年前
        1
  •  8
  •   gerdemb    16 年前

    有时候,没有什么比向别人描述一个问题来帮助你解决它更简单的了。:)我应该像这样将python字符串标记为unicode,现在一切都可以工作了:

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