views:

45

answers:

1

I'm using the Assets plugin in my Catalyst app, and I would like some javascript and css 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.

+3  A: 

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>
phaylon
Beautiful. Thanks.
Felix
I don't think `MooseX::Types::Moose` is necessary here -- the native attribute helpers are part of Moose core.
Ether
@Ether: You're right, one could use the string-form. I am just used to using MooseX-Types everywhere.
phaylon
ah, you've left off quotes around `ArrayRef[Str]` -- it took a minute to see the difference. :)
Ether
I just wanted to say thanks again Phaylon. This has been a much nicer solution than either I had been considering.
Felix
As Phaylon says putting it in the chained root is probably a good idea then different 'classes' of pages can have different sets of assets - not simply all pages created by this view.
cubabit