-
Notifications
You must be signed in to change notification settings - Fork 580
Working with helpers
Mojolicious allows you to create "helpers" which are little bits of code that can be easily called from other portions of your application, especially templates. Helpers can be installed two ways. The easiest way is to add a line(s) to the startup subroutine of your application.
$self->helper(myhelper => sub { return 'I am your helper!' });
To use this helper you add a block of code to your template(s)
<%== myhelper %>
When you display the page you should see the phrase 'I am your helper!' displayed in your browser. You can install as many helpers as you want as long as they have unique names. Helpers are just like subs, you can pass in arguements from the template. For example
$self->helper(myhelper => sub {
my $self = shift;
my $name = shift || "your";
return 'I am $name helper!'
});
Then in the template you would have:
<%== myhelper("Bob's") %>
When you display the page, you should see the phrase
I am Bob's helper!
displayed in your browser.
Another way to use helpers is to install them as a plugin. A plugin needs to be registered before use Registering and using plugins requires 4 steps.
1) Create the package file that will hold the plugin(s)
2) Register the plugin with Mojolicious
3) Add some markup to your template to call that helper
STEP 1: Create a new file to hold your helpers. Let's 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 Helpers.pm would look something like this...
package Myapp::Helpers;
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: Then, somewhere in your Myapp.pl (or Myapp) file you need to register that plugin. Mojolicious will load it automatically.
$self->plugin('MyApp::Helpers');
STEP 3: Modify one of your templates and include the following code.
<%= 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.