0

我想使用 Cheetah 模板引擎渲染一个带有 Unicode 字符的变量。

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

This is static text in the template: äöü
This is filled by Cheetah: $variable

我的程序加载该文件,并插入一个变量variable

from Cheetah.Template import Template

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

# open template
templateFile = open('template.txt', 'r')
templateString = templateFile.read()
templateFile.close()

template = Template(templateString, data)
filledText = str(template)

# Write filled template
filledFile = open('rendered.txt', 'w')
filledFile.write(filledText)
filledFile.close()

这将创建一个文件,其中静态 Unicode 字符很好,但动态字符被替换字符替换。

This is static text in the template: äöü
This is filled by Cheetah: ���

所有文件都是 UTF-8,以防万一。

如何确保正确生成字符?

4

1 回答 1

1

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

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

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

filledFile = codecs.open('rendered.txt', 'w', encoding='utf-8')

unicode()使用而不是获取结果str()

这不是必需的,但建议使用 - 添加#encoding utf-8到模板中:

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

请参阅 Cheetah 测试中的示例:https ://github.com/CheetahTemplate3/cheetah3/blob/master/Cheetah/Tests/Unicode.py 。

于 2018-03-10T20:50:49.587 回答