Component plugins

Component plugins are plugins that define components. Components usually access the database and define with their own models.

Here we turn the previous comments component into a comments_plugin by using the same code we wrote before, but following all of the previous rules.

First, we create a model called “models/plugin_comments.py”:

  1. db.define_table('plugin_comments_comment',
  2. Field('body', 'text', label='Your comment'),
  3. auth.signature)
  4. def plugin_comments():
  5. return LOAD('plugin_comments', 'post', ajax=True)

(notice the last two lines define a function that will simplify the embedding of the plugin)

Second, we define a “controllers/plugin_comments.py”

  1. def post():
  2. if not auth.user:
  3. return A('login to comment', _href=URL('default', 'user/login'))
  4. comment = db.plugin_comments_comment
  5. return dict(form=SQLFORM(comment).process(),
  6. comments=db(comment).select())

Third, we create a view called “views/plugin_comments/post.load”:

  1. {{for comment in comments:}}
  2. <div class="comment">
  3. on {{=comment.created_on}} {{=comment.created_by.first_name}}
  4. says <span class="comment_body">{{=comment.body}}</span>
  5. </div>
  6. {{pass}}
  7. {{=form}}

Now we can use admin to pack the plugin for distribution. Admin will save this plugin as:

  1. web2py.plugin.comments.w2p

We can use the plugin in any view by simply installing the plugin via the edit page in admin and adding this to our own views

  1. {{=plugin_comments()}}

Of course we can make the plugin more sophisticated by having components that take parameters and configuration options. The more complex the components, the more difficult it becomes to avoid name collisions. The Plugin Manager described below is designed to avoid this problem.