我在使用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éptimoCine”)。
呈现的模板如下所示:
...
<title>S\u00e9ptimo Cine</title>
...
我希望它是:
...
<title>Séptimo Cine</title>
...
我已经进行了几次测试,但是无法正常工作。
我尝试设置没有.encode(“ utf8”)的title变量,但是会引发异常(ValueError:预期为字节对象,而不是unicode对象),所以我的猜测是初始消息是unicode
我已经使用chardet.detect来获取消息的编码(为“ ascii”),然后执行以下操作:myvar.decode(“ ascii”)。encode(“ cp852”),但标题仍无法正确呈现。
我还确保我的模板是UTF-8文件,但没有任何区别。
有关如何执行此操作的任何想法?
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()
-金贾要统一。因此,假设您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", "w") 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'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句