如何在web.py模板中导入模块?
我有一段代码:
render = web.template.render('templates/')
app = web.application(urls, globals())
我在web.py 的食谱中读到了模板导入的内容。
现在,当我尝试在一个模板中导入re
时:
render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())
我遇到了一个错误:
<type 'exceptions.TypeError'> at /'dict' object is not callable
错误信息中显示了这一行:app = web.application(urls, globals())
。
但是当我修改成这样:
app = web.application(urls)
错误就消失了,re
成功导入到我的模板中。
我不明白为什么在web.template.render
中使用globals={'re': re}
会导致问题?
为什么我不能像第二个例子那样同时保留两个全局变量呢?
1 个回答
5
我猜你的脚本或模板里还有其他的东西在引起这个错误。如果你能提供一个完整的例子,那就更容易找出问题了。这里有一个可以正常工作的例子:
import web
import re
urls = ('/', 'index')
render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())
class index:
def GET(self):
args = web.input(s='')
return render.index(args.s)
if __name__ == '__main__':
app.run()
还有模板,index.html:
$def with(s)
$code:
if re.match('\d+', s):
num = 'yes'
else:
num = 'no'
<h1>Is arg "$:s" a number? $num!</h1>
你可以访问 http://localhost:8080/?s=123 来试试。