Mojolicious-Plugin-ContextResources
view release on metacpan or search on metacpan
lib/Mojolicious/Plugin/ContextResources.pm view on Meta::CPAN
package Mojolicious::Plugin::ContextResources;
use Mojo::Base 'Mojolicious::Plugin';
use File::Spec::Functions qw(catfile);
our $VERSION = '0.02';
# Get current context path
sub _context($) {
my ($c) = @_;
my @path;
my $stash = $c->stash;
if( $stash->{'controller'} && $stash->{'action'} ) {
push @path, split m{[/\-]}, $stash->{'controller'};
push @path, $stash->{'action'};
} elsif( $stash->{'mojo.captures'}{'template'} ) {
push @path, $stash->{'mojo.captures'}{'template'};
}
return @path;
}
sub register {
my ($self, $app, $conf) = @_;
$conf ||= {};
# Path
$conf->{home} //= $app->home;
$conf->{public} //= 'public';
$conf->{js} //= '/js';
$conf->{css} //= '/css';
$app->helper(url_context_stylesheet => sub {
my ($c) = @_;
my @path = _context( $c );
return undef unless @path;
my $file = catfile( $conf->{css}, @path ) . '.css';
my $path = $conf->{home}->rel_file(catfile $conf->{public}, $file);
return undef unless -f $path;
return Mojo::URL->new( $file );
});
$app->helper(url_context_javascript => sub {
my ($c) = @_;
my @path = _context( $c );
return undef unless @path;
my $file = catfile( $conf->{js}, @path ) . '.js';
my $path = $conf->{home}->rel_file(catfile $conf->{public}, $file);
return undef unless -f $path;
return Mojo::URL->new( $file );
});
$app->helper(stylesheet_context => sub {
my ($c) = @_;
my $url = $c->url_context_stylesheet;
return Mojo::ByteStream->new('') unless $url;
return Mojo::ByteStream->new( $c->stylesheet( $url ));
});
$app->helper(javascript_context => sub {
my ($c) = @_;
my $url = $c->url_context_javascript;
return Mojo::ByteStream->new('') unless $url;
return Mojo::ByteStream->new( $c->javascript( $url ));
( run in 0.676 second using v1.01-cache-2.11-cpan-71847e10f99 )