如何将模块导入web.py模板?

psy*_*cat 0 python web.py

我有以下代码:

render = web.template.render('templates/')
app = web.application(urls, globals())
Run Code Online (Sandbox Code Playgroud)

我在web.py食谱中阅读了有关模板导入的信息。

现在,当我尝试导入re模板时:

render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

<type 'exceptions.TypeError'> at /'dict' object is not callable
Run Code Online (Sandbox Code Playgroud)

并且该行在traceback中显示:app = web.application(urls, globals())

但是当我修改它时:

app = web.application(urls)
Run Code Online (Sandbox Code Playgroud)

错误消失了,并re导入到我的模板中。

我不明白如何globals={'re': re}web.template.render休息呢?

为什么我不能像第二个示例那样保留两个全局变量?

dav*_*avr 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()
Run Code Online (Sandbox Code Playgroud)

还有模板index.html:

$def with(s)

$code:
    if re.match('\d+', s):
        num = 'yes'
    else:
        num = 'no'

<h1>Is arg "$:s" a number? $num!</h1>
Run Code Online (Sandbox Code Playgroud)

浏览到http:// localhost:8080 /?s = 123进行尝试。