【问题标题】:Jinja2 encoding to renderJinja2 编码来渲染
【发布时间】:2014-02-14 04:09:52
【问题描述】:

我有一个 python 字符串:

<p> <a href="http://blog.alexmaccaw.com/how-to-travel-around-the-world-for-a-year">How to travel around the world for a year • Alex MacCaw<span class="small">blog.alexmaccaw.com</span> </a></p>

&lt;type 'str'&gt;

当我尝试使用 Jinja 渲染它时,问题是由 引起的。

renderedPage = template.render(starred = the_string_i_mentioned_higher_up)

最后出现这个错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 125: ordinal not in range(128)

我尝试了各种编码和解码,但总是遇到类似的错误。

有什么想法吗?

【问题讨论】:

  • 如何获得the_string_i_mentioned_higher_up 或它是如何编码的?您是按字面意思声明的吗?

标签: python python-2.7 unicode ascii jinja2


【解决方案1】:

尝试使用html代码:

&middot;

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在 Python 2 中对文本使用 unicode,而不是 str 对象。尤其是对于非 ASCII 字符的文本。 str 有时只是巧合。

    (如果源文件中有非 ASCII 文本,还需要指定源编码):

    # coding: utf-8
    mystring = u'<p> <a href="http://blog.alexmaccaw.com/how-to-travel-around-the-world-for-a-year">How to travel around the world for a year • Alex MacCaw<span class="small">blog.alexmaccaw.com</span> </a></p>'
    

    (在 Python 代码中而不是在模板或数据库中包含 HTML 可能也是一个坏主意...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2013-10-09
      • 2019-06-28
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多