[Catalyst] View Helpers?

André Walker andre at andrewalker.net
Fri Feb 15 00:34:54 GMT 2013


On Thu, Feb 14, 2013 at 06:08:59PM -0600, Kevin Monceaux wrote:
>     [% c.LinkTo('Recipes', 'recipe/list') %]
> 
> If so, how does one make a function available in views via the CATALYST_VAR,
> and where is the best place for such a function's code in a Catalyst
> project?

All you have to do is to define a "sub LinkTo {}" in lib/MyApp.pm, and it
would be globally accessible throughout your application (in $c, CATALYST_VAR,
or whatever).

I'm not saying that's the best approach though. What I usually do is to create
a sort of uri_for clone for my templates, without ever letting them know about
the CATALYST_VAR. I don't want my templates to use the 'c' variable, or even
be aware that they are being loaded inside of Catalyst.

So in my View class:

    extends 'Catalyst::View::TT';

    sub uri_for {
        my ( $self, $c, $uri ) = @_;
        return $c->uri_for($uri);
    }

And in the templates:

    [% uri_for('/recipe/list') %]

You could easily create your LinkTo method in your View class, so that it
would be mockable and replaceable, making your templates testable and reusable :)

Regards,
André




More information about the Catalyst mailing list