【问题标题】:Jinja2 weird encoding errorJinja2 奇怪的编码错误
【发布时间】:2012-12-27 10:02:43
【问题描述】:

我已经为此奋斗了整整一个晚上......

我正在尝试使用 Python markdown 从 .md 文件生成 HTML 文件并将它们嵌入到其他一些 HTML 文件中。

这是有问题的sn-p:

md = markdown.Markdown(encoding="utf-8")
input_file = codecs.open(f, mode="r", encoding="utf-8") # f is the name of the markdown file
text = input_file.read()
html = md.convert(text) # html generated from the markdown file

context = {
    'css_url': url_for('static', filename = 'markdown.css'),
    'contents': html
}

rendered_file = render_template('blog.html', **context)
output = open(splitext(f)[0] + '.html', 'w') # write the html to disk
output.write(rendered_file)
output.close()

这是我的“blog.html”模板,非常简单:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>blog</title>
  <link rel="stylesheet" href="{{ css_url }}" type="text/css" />
</head>

<body>
  {{ contents }}
</body>

</html>

然而这就是我得到的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>blog</title>
  <link rel="stylesheet" href="/static/markdown.css" type="text/css" />
</head>

<body>
&lt;li&gt;People who love what they are doing&lt;/li&gt;
&lt;li&gt;&lt;/li&gt;
&lt;/ol&gt;
</body>

</html>

所以我得到了那些奇怪的“&gt”、“&lt”的东西,即使我已经将编码指定为“utf-8”。可能会出什么问题?

谢谢!

【问题讨论】:

    标签: python markdown jinja2


    【解决方案1】:

    &amp;lt;&amp;gt; 与编码无关。这些是代表您输入的 HTML 实体。你应该mark it as safe 这样jinja 就不会自动逃脱它。

    {{ contents|safe }}
    

    【讨论】:

    • 天哪,你刚刚救了我的命...非常感谢!!
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多