在Jinja2 temp中使用utf-8字符

2024-06-15 03:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在用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>
...

我已经做了几次测试,但我不能让它起作用。

  • 我试图在没有的情况下设置title变量。encode(“utf8”),但它抛出了一个异常(ValueError:Expected a bytes object,not a unicode object),所以我猜初始消息是unicode

  • 我使用了chardet.detect获取消息的编码(它是“ascii”),然后执行了以下操作:myvar.decode(“ascii”).encode(“cp852”),但标题仍然没有正确呈现。

  • 我还确保了我的模板是一个UTF-8文件,但它没有什么不同。

有什么办法吗?


Tags: 模板消息indextitlehtmltemplateutf8variables
3条回答

尝试将“渲染”命令更改为。。。

template.render(index_variables).encode( "utf-8" )

Jinja2的文档说“这将把呈现的模板作为unicode字符串返回。”

http://jinja.pocoo.org/docs/api/?highlight=render#jinja2.Template.render

希望这有帮助!

如果因为混合了多种语言而什么都不起作用——就像我的例子一样——只需将“utf-8”替换为“utf-16”

此处的所有编码选项:

https://docs.python.org/2.4/lib/standard-encodings.html

TL;博士:

  • Pass Unicodetemplate.render()
  • 在将呈现的unicode结果写入文件之前,将其编码为bytestring

这让我困惑了一段时间。因为你知道

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。因此,在将结果写入文件之前,需要将其编码为bytestring:

index_file.write(output.encode('utf-8'))

第二个错误是将由testring编码的utf-8传递给template.render()-Jinja wants 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", "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'))

相关问题 更多 >