Altering TT's INCLUDE_PATH in Dancer with Custom View

Altering Template Toolkit's INCLUDE_PATH in Dancer

This just came up on Dancer's mailing list and I've been sitting on this code (and post) for a few months since the project I was working on didn't need it.

Basically Dancer's Template Toolkit view requires you completely alter it or use the default setting. This is pain if you just want to add to it but not have to manage all the changes.

I created a new TT view class, to get inside the TT init and add to the INCLUDE_PATH instead of replace it. The code was a bit involved and I extended it a bit by adding a customization flag in each environment (if needed).

On to the code

Here is the code and config that i used to do this

# snip
template: "custom_views_template"
engines:
custom_views_template:
encoding: 'utf8'
start_tag: '[%'
end_tag: '%]'
PRE_PROCESS: 'common/shared.tt'
WRAPPER: 'wrapper.tt'
TRIM: 1
# base directory for customizations
custom_path: 'custom'
customization: 'monkey'
view raw config.yml hosted with ❤ by GitHub
package Dancer::Template::CustomViewsTemplate;
use strict;
use warnings;
use Carp;
use Dancer::Config 'setting';
use Dancer::Logger;
use Dancer::ModuleLoader;
use Dancer::Exception qw(:all);
use Dancer::FileUtils qw( path );
use base qw( Dancer::Template::TemplateToolkit );
# might want to add singleton here
sub custom_views {
my $self = shift;
# not configured properly
return undef
unless $self->config->{custom_path};
return setting('customization') ?
path( setting('appdir'),
$self->config->{custom_path},
setting('customization'), # this pulls subdir from env settings file
'views' )
: undef;
}
sub init {
my $self = shift;
if ( my $custom_view = $self->custom_views ) {
$self->config->{INCLUDE_PATH} = join ':', $custom_view, setting('views')
}
$self->SUPER::init( @_ );
}
# need to search custom_views then views dir for template
sub view {
my ($self, $view) = @_;
my @search_views = ( $self->custom_views, setting('views') );
foreach my $views_dir (@search_views) {
foreach my $template ( $self->_template_name($view) ) {
my $view_path = path($views_dir, $template);
return $view_path if -f $view_path;
}
}
return;
}
1;

Disclaimer

I don't recall all the other issues that i ran into while doing this. It was over 6 months ago but post questions if you have them

__END__

Comments

Post a Comment

Popular posts from this blog

BootstrapX clickover

Changing Dancer::Plugin::Ajax's content type

2 ways to get SQLite to put dates into columns