Working with helpers

kberov edited this page Dec 19, 2014 · 13 revisions

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/ (this example assumes your lib path is correct). The contents of 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!'; });



STEP 2: Then, somewhere in your (or Myapp) file you need to register that plugin. Mojolicious will load it automatically.


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.