Jinja2 返回空页面

0 投票
1 回答
820 浏览
提问于 2025-04-18 17:00

我正在使用 Jinja2 和 Python 3.3.1,下面是我的模板代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />

  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}" />
</head>

<body>

<div id="content">
  <p>Why, hello there!</p>
</div>

</body>
</html>

我的 python.cgi 文件内容如下:

from jinja2 import Template
print("Content-type: text/html\n\n")

templateLoader = jinja2.FileSystemLoader( searchpath="\\")
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "cgi-bin/example1.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )

templateVars = { "title" : "Test Example",
               "description" : "A simple inquiry of function." }
outputText = template.render( templateVars )

但是我看到的只是一个空白页面,没有任何 HTML 内容。虽然 CGI 头部是正常工作的,浏览器也能识别这是 HTML,但“你好啊”这句话却没有显示出来。Jinja2 也能正常工作,因为在解释器模式下我创建了一个简单的模板,内容是:

t = Template("hello! {{title}}")
t.render(title="myname")

结果显示了“你好!我的名字”。

错误日志里也没有任何问题。到底发生了什么呢?

1 个回答

1

Python解释器会自动显示任何表达式的结果,只要这个结果不是None

在CGI脚本中,你需要明确地把结果输出:

outputText = template.render( templateVars )
print(outputText)

template.render() 只会生成字符串结果,但它不会自动把这个结果写到标准输出(stdout)中。

撰写回答