简体   繁体   English

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

[英]How to import modules into web.py templates?

I have following piece of code: 我有以下代码:

render = web.template.render('templates/')
app = web.application(urls, globals())

I read about template imports in the web.py cookbook . 我在web.py食谱中阅读了有关模板导入的信息。

Now, when I try to import re in a template: 现在,当我尝试将re导入模板时:

render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())

I got an error: 我收到一个错误:

<type 'exceptions.TypeError'> at /'dict' object is not callable

and this line showed in the traceback: app = web.application(urls, globals()) . 并在回溯中显示此行: app = web.application(urls, globals())

But when I modify it: 但是当我修改它时:

app = web.application(urls)

the error is gone, and re is imported in my template. 错误消失了,并且re导入了我的模板。

I don't understand how globals={'re': re} in web.template.render breaks it? 我不明白web.template.render globals={'re': re} web.template.render破坏它?

Why I can't keep both globals as in second example? 为什么我不能像第二个示例那样保留两个全局变量?

I'm guessing there is something else you are doing in your script or template that is causing that error. 我猜您在脚本或模板中所做的其他事情导致了该错误。 If you showed the complete example, then it would be easier to see. 如果显示了完整的示例,那么将更容易看到。 Here is a working example: 这是一个工作示例:

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()

And the template, index.html: 还有模板index.html:

$def with(s)

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

<h1>Is arg "$:s" a number? $num!</h1>

Browse to http://localhost:8080/?s=123 to try it. 浏览到http:// localhost:8080 /?s = 123进行尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM