在用Jinja2呈现模板时,我尝试使用utf-8字符。下面是我的模板的样子:
<!DOCTYPE HTML>
<html manifest="" lang="en-US">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
...title变量设置如下所示:
index_variables = {'title':''}
index_variables['title'] = myvar.encode("utf8")
template = env.get_template('index.html')
index_file = open(preview_root + "/" + "index.html", "w")
index_file.write(
template.render(index_variables)
)
index_file.close()现在,问题是myvar是从消息队列中读取的消息,可以包含这些特殊的utf8字符(例如。"Séptimo Cine")。
呈现的模板如下所示:
...
<title>S\u00e9ptimo Cine</title>
...我希望它是:
...
<title>Séptimo Cine</title>
...我做了几次测试,但我做不到。
对怎么做有什么想法吗?
发布于 2014-03-04 20:47:48
TL;DR:
template.render()这让我困惑了一段时间。因为你知道
index_file.write(
template.render(index_variables)
)在一条语句中,这基本上只是Python关注的一行,因此您得到的跟踪是误导的:我在重新创建测试用例时得到的异常不是发生在template.render(index_variables)中,而是在index_file.write()中。所以像这样把代码分开
output = template.render(index_variables)
index_file.write(output)是诊断UnicodeEncodeError在哪里发生的第一步。
Jinja返回unicode,您可以让它呈现模板。因此,在将结果写入文件之前,需要将结果编码为字节串:
index_file.write(output.encode('utf-8'))第二个错误是将utf-8编码的字节串传递给template.render() - Jinja想要unicode。因此,假设您的myvar包含UTF-8,您需要首先将其解码为unicode:
index_variables['title'] = myvar.decode('utf-8')所以,把所有这些放在一起,这对我来说是可行的:
# -*- coding: utf-8 -*-
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myproject', 'templates'))
# Make sure we start with an utf-8 encoded bytestring
myvar = 'Séptimo Cine'
index_variables = {'title':''}
# Decode the UTF-8 string to get unicode
index_variables['title'] = myvar.decode('utf-8')
template = env.get_template('index.html')
with open("index_file.html", "wb") as index_file:
output = template.render(index_variables)
# jinja returns unicode - so `output` needs to be encoded to a bytestring
# before writing it to a file
index_file.write(output.encode('utf-8'))发布于 2014-03-04 20:47:39
试着把你的渲染命令改为.
template.render(index_variables).encode( "utf-8" )Jinja2 2的文档说:“这将将呈现的模板返回为unicode字符串。”
http://jinja.pocoo.org/docs/api/?highlight=render#jinja2.Template.render
希望这能有所帮助!
发布于 2016-11-05 20:16:16
将下面的行添加到脚本的开头,它将正常工作,不会有任何进一步的更改:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")https://stackoverflow.com/questions/22181944
复制相似问题