Python 如何在Cheetah模板中呈现unicode字符?

Python 如何在Cheetah模板中呈现unicode字符?,python,cheetah,Python,Cheetah,我想使用Cheetah模板引擎呈现一个带有Unicode字符的变量 我的模板文件template.txt如下所示: 这是模板中的静态文本:äöü 这是由Cheetah:$variable填充的 我的程序加载该文件,并插入一个变量: 从Cheetah.Template导入模板 数据=[{变量:äöü}] 打开模板 templateFile=打开'template.txt','r' templateString=templateFile.read templateFile.close templat

我想使用Cheetah模板引擎呈现一个带有Unicode字符的变量

我的模板文件template.txt如下所示:

这是模板中的静态文本:äöü 这是由Cheetah:$variable填充的 我的程序加载该文件,并插入一个变量:

从Cheetah.Template导入模板 数据=[{变量:äöü}] 打开模板 templateFile=打开'template.txt','r' templateString=templateFile.read templateFile.close template=TemplatetemplateString,数据 filledText=strtemplate 写填充模板 filledFile=打开'rendered.txt','w' filledFile.WriteFileText filledFile.close 这将创建一个文件,其中静态Unicode字符可以使用,但动态字符将替换为替换字符

这是模板中的静态文本:äöü 这是由猎豹填写的:��� 所有文件都是UTF-8,以防万一


如何确保正确生成字符?

将所有字符串设置为unicode,包括文件中的字符串:

data = [{"variable" : u"äöü"}]

templateFile = codecs.open('template.txt', 'r', encoding='utf-8')

filledFile = codecs.open('rendered.txt', 'w', encoding='utf-8')
使用unicode而不是str获取结果

这不是必需的,但推荐使用-将编码utf-8添加到模板中:

#encoding utf-8
This is static text in the template: äöü
This is filled by Cheetah: $variable

请参阅猎豹测试中的示例:。

谢谢!补充一点:当使用python3时,您不需要使用codec,因为open中也提供了编码参数。您也不需要用u标记字符串。因此,您只需要在每次文件打开操作中提供编码。我仍在使用Python 2.7,并以可移植的方式编写代码:-