組件被定義為網頁的功能部分,它可以自主運行.它可以由嵌入在網頁中的模塊,控制器和視圖組成.應用程序中的組件必須是本地化標記,并且性能被視為獨立于模塊.
在web2py中,主要關注的是使用在頁面中加載的組件以及哪些內容進行通信通過AJAX與組件控制器一起使用.
web2py包含一個函數,稱為 LOAD 函數,無需顯式JavaScript或AJAX編程即可輕松實現組件.
考慮一個簡單的Web應用程序,即" test ",它使用文件" models/db_comments.py 中的自定義模型擴展web2py應用程序".
db.define_table( 'comment_post', Field('body','text', label = 'Your comment'),auth.signature)
上面的代碼將創建一個表" comment_post "使用正確的表定義.該行動將在" controllers/comments.py "中的功能幫助下實施.
def post(): return dict( form = SQLFORM(db.comment_post).process(), comments = db(db.comment_post).select() )
相應的視圖將顯示為 :
{{extend 'layout.html'}}{{for post in comments:}}<div class = "post"> On {{= post.created_on}} {{= post.created_by.first_name}} says <span class = "post_body">{{= post.body}}</span></div>{{pass}}{{= form}}
可以使用給定的URL訪問該頁面 : 去; http://127.0.0.1:8000/test/comments/post
上述方法是一種訪問視圖的傳統方式,可以更改實現LOAD函數.
這可以通過創建一個擴展名為".load"但不擴展布局的新視圖來實現.
創建的新視圖將是"views/comments/post.load" :
<div class = "post"> On {{= post.created_on}} {{= post.created_by.first_name}} says <blockquote class = "post_body">{{= post.body}}</blockquote></div>{{pass}}{{= form}}
訪問該頁面的URL將是 : 去; http://127.0.0.1:8000/test/comments/post.load
LOAD組件可以嵌入到web2py應用程序的任何其他頁面中.這可以通過使用以下語句來完成.
{{= LOAD('comments','post.load',ajax = True) }
例如,控制器可以編輯為 :
def index(): return dict()
在查看中,我們可以添加組件 :
{{extend'layout.html'}} {{= LOAD('comments' ,'post.load',ajax = True)}}
可以使用URL : 訪問該頁面; http://127.0.0.1:8000/test/default/index
組件插件
組件插件是插件,唯一定義組件.組件直接使用其模型定義訪問數據庫.
如上例所述, comments_plugin 中的注釋組件可以在 Models
" models/plugin_comments.py " :
db.define_table( 'plugin_comments_comment', Field('body','text', label = 'Your comment'), auth.signature)
控制器將包含以下插件 :
def plugin_comments(): return LOAD('plugin_comments','post',ajax = True)
免責聲明:以上內容(如有圖片或視頻亦包括在內)有轉載其他網站資源,如有侵權請聯系刪除