我在python 3.3.1中使用Jinja2,我的模板代码如下:
<!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-header正常工作,表示浏览器正在识别其html,但未显示“为什么,你好”。jinja2也可以工作,因为在解释器模式下,我创建了一个简单的模板,如:
t = Template("hello! {{title}}")
t.render(title="myname")
并显示你好!我的名字
在error_log中也没有错。这是怎么回事?
只要不返回表达式,Python解释器就会自动回显任何表达式的结果None
。
在CGI脚本中,您需要显式写出结果:
outputText = template.render( templateVars )
print(outputText)
template.render()
仅产生字符串结果,不会为您将其写入stdout。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句