建立views ,使用grok

利用 grok.View, 建立views(BrowserView)更有威力

由於grok會自動掃描在目錄中所有的py檔,所以建立views,可以直接在模組目錄下以python code建立views, 例:

from five import grok
from zope.interface import Interface

grok.templatedir('templates')

class Subscribe(grok.View):

    grok.template('subscribe')
    grok.context(Interface)
    grok.require('zope2.View')

    def update(self):
        return 'hello update'

grok.templatedir() 是宣告模版在那個目錄,這是grok.templatedir 是 modules level,只能放在程式的最上層

grok.template() 是宣告模版檔名,不用加副檔名 .pt, grok會自已掃描,grok.template 是class level, 只能放在 class 層,不能放在 function 裏面

grok.context() 宣告那些interface可以使用這個views, Interface 就是全站適用,若改為其他 Interface, 就只能在指定的 interface 下使用

grok.require() 宣告權限

grok預設會使用class name的小寫做為url的一部份,以本例而言,網址就可能會是 http://www.example.com/subscribe

另外還可以使用

grok.name(),可以改變url

拜訪views時,預設會執行 update() , 如此拿來做表單就很適合了

如果不使用template,則必需使用 render() 來回傳結果供前端使用