-
Notifications
You must be signed in to change notification settings - Fork 582
Working with helpers
Mojolicous allows you to create "helpers" which are little bits of code that you can be easily called from other portions of your application, especially templates. Helpers can be installed two ways. The easiest way is to simply add a line(s) to the startup subroutine of your application.
$self->helper(myhelper => sub { return 'I am a your helper!' });
To use this helper you simply add a block of code to your template(s)
<%== myhelper %>
When you display the page you should see the phrase 'I am a your helper!' displayed in your browser. You can install as many helpers as you want as long as they have unique names.
Another way to use helpers is to install them as a plugin. This is a little bit trickier since plugins need to be registered. Registering and using plugins requires 4 steps.
1) Create the package file that will hold the plugin(s) 2) Call (use) that package in your application 3) Register the plugin with Mojolicious 4) Add some markup to your template to call that helper
STEP 1: Create a new file to hold your helpers. Lets assume our application is named Myapp and our helpers are going to be installed in a file named lib/Helpers.pm (this example assumes your lib path is correct). The contents of you Helpers.pm would look something like this...
package Myapp::Helpers;
use strict;
use warnings;
use base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
$app->helper(mypluginhelper =>
sub { return 'I am your helper and I live in a plugin!'; });
}
1;
STEP 2: Now, in your Myapp.pl (or just Myapp) file you will need to call that package, like this...
use Myapp::Helpers;
STEP 3: Then, somewhere in your Myapp.pl (or Myapp) file you need to register that plugin. Like this...
Mojolicious::Plugins->register_plugin('Myapp::Helpers', 'Myapp');
STEP 4: Modify one of your templates and include the following code.
<%== Myapp->mypluginhelper %>
Now restart your webserver and load the page. You should see the message. 'I am your helper and I live in a plugin!'.
Enjoy your new plugins.