Accessing the Catalyst object $c from MyApp.pm
I'm using the Assets plugin in my Catalyst app, and I would like some javascript and c开发者_如何学JAVAss files included in the assets of every page.
My first thought is call $c->assets->include('file.js') from MyApp/lib/MyApp.pm where I do setup and config, but I don't know how to get a hold of $c there.
My next idea involves using the WRAPPER stuff, and placing calls like [% c.assets.include('file.js') %] in default html template, but the calls dump the object information to the page, so the calls would have to be uglied up to suppress output.
Solutions or new ideas appreciated. Thanks in advance.
There is no context object yet during application setup, since the $c represents the current request.
If you are using Chained, you can do the call in your root chain action. If you use the non-Chained action types like Local, Path, etc. you can put a begin action in your root controller.
The most correct way in my opinion is however to extend the view. Here's some example code:
package MyApp::View::HTML;
use Moose;
use MooseX::Types::Moose qw( ArrayRef Str );
use namespace::autoclean;
extends 'Catalyst::View::TT';
has common_assets => (
traits => [qw( Array )],
isa => ArrayRef[Str],
handles => {
common_assets => 'elements',
},
);
before process => sub {
my ($self, $ctx) = @_;
$ctx->assets->include($_)
for $self->common_assets;
};
1;
Then you can configure it with something like this:
<view HTML>
common_assets foo.css
common_assets bar.js
</view>
精彩评论