2011-02-18 38 views
0

我有下面這段代碼:如何將模塊導入到web.py模板中?

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

我讀到的web.py cookbook模板進口。

現在,當我嘗試在模板導入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在我的模板導入。

我不明白globals={'re': re}web.template.render打破了嗎?

爲什麼我不能像第二個例子那樣保留兩個全局變量?

回答

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嘗試。

+0

謝謝你的例子!我今天意外地發現了這個問題,當我重新啓動服務器 - 代碼工作。我的錯。 – vladimirze 2011-02-19 08:48:49