Skip to content

Working with helpers

l8gravely edited this page Jun 29, 2011 · 7 revisions

Working with Helpers

Mojolicous 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) 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. 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 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...

$self->plugin('MyApp::Helpers');

STEP 4: 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!'.

[ TODO: show use of parameters in helpers. ]

Enjoy your new plugins.

Clone this wiki locally