choroba has asked for the wisdom of the Perl Monks concerning the following question:
| choroba |
In the first versions, I used ugly Template code to turn a number into the “fence”. The, I realised it's possible to create filters. I googled for the details and found the following email. It shows a way how a custom filter can be created:
# config file: engines: template_toolkit: PLUGIN_BASE: 'Template::Plugin' # The filter code: package Template::Plugin::FilterFence; use Template::Plugin::Filter; use base qw( Template::Plugin::Filter ); sub filter { my ($self, $text) = @_; return join ' ' # etc } 1; # The template that uses the filter: <% USE FilterFence %> <div id="main"> <table> <% FOREACH row IN rows %> <tr><td><% row.0 %><td><% row.1 | $FilterFence %> <% END %> </table> </div>
It worked for me, too. I even added a test file for the filter:
use Test::More; use Template::Plugin::FilterFence; my $t = 'Template::Plugin::FilterFence'->new; is($t->filter(0), q(), 'zero'); is($t->filter(1), '|', 'one'); # etc.
But I didn't like the dollar sign needed in the template file in front of the filter name. I asked on Dancer's IRC channel and was pointed to the “Example” section of Template::Plugin::Filter. So, I added the init sub to the filter:
sub init { my $self = shift; $self->install_filter('fence'); return $self }
... and changed the template code to simpler
<% row.1 | fence %>
But, my test started to fail with the following error:
Can't call method "define_filter" on an undefined value at .../Templat +e/Plugin/Filter.pm line 117.
It seemed like the filter tried to register itself to a template, which didn't exist. The first workaround I discovered was to fake the creation of the filter object:
my $t = bless {}, 'Template::Plugin::FilterFence';
It fixed the test, but I didn't like it. What if an important thing is missing in such an object? So I experimented more and discovered deleting the init sub also solved the problem:
undef *Template::Plugin::FilterFence::init;
I don't like this solution much, either. Is there a clean way how to run a custom filter in isolation to test it?
Update: Removed the original example, used a variant of the existing code to avoid confusion.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Testing Custom Template Filters in Dancer
by Anonymous Monk on Feb 06, 2015 at 07:55 UTC | |
|
Re: Testing Custom Template Filters in Dancer
by Anonymous Monk on Feb 05, 2015 at 22:25 UTC | |
by Anonymous Monk on Feb 05, 2015 at 23:07 UTC |