Categories: Web2py教程

Web2py-组件

组件被定义为网页的功能部分,它可以自主工作。它可以由嵌入在网页中的模块,控制器和视图组成。应用程序中的组件必须是本地化标签,并且性能被认为与模块无关。

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

View中,我们可以添加组件:

{{extend 'layout.html'}}
{{= LOAD('comments','post.load',ajax = True)}}

可以使用URL访问该页面:http://127.0.0.1:8000/test/default/index

组件插件

组件插件是唯一定义Components的插件。组件使用其模型定义直接访问数据库。

如前面的示例所述,可以在“模型”部分中将comment组件添加到comments_plugin中-

“ 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)
terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

4 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

1 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

2 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

3 周 ago