0

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

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

这是有问题的片段:

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>

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

谢谢!

4

1 回答 1

2

&lt;&gt;与编码无关。这些是代表您输入的 HTML 实体。您应该将其标记为安全,这样 jinja 就不会自动逃脱它。

{{ contents|safe }}
于 2013-01-13T07:49:22.337 回答