【问题标题】:How to render unicode characters in a Cheetah template?如何在 Cheetah 模板中呈现 unicode 字符?
【发布时间】:2018-03-10 20:33:16
【问题描述】:

我想使用 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,以防万一。

如何确保正确生成字符?

【问题讨论】:

    标签: python cheetah


    【解决方案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

    【讨论】:

    • 谢谢!添加到这个答案:使用python3时,您不需要使用codecs(因为open中也提供了编码参数。您也不需要用u标记字符串。因此,您只需在每次文件打开操作时提供encoding
    • 我仍在使用 Python 2.7 并以可移植的方式编写代码。 :-)
    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多