[Dancer-users] Custom FILTERS for TemplateToolkit in dancer?

ambs ambs+dancer at perl-hackers.net
Thu Oct 13 12:31:11 CEST 2011


On 13/10/2011 01:25, Assaf Gordon wrote:
> Assaf Gordon wrote, On 10/12/11 19:06:
>> Has anyone managed to add a custom Template-Toolkit Filter when using Dancer ?
>
> Answering myself...
>
> During initialization (when Dancer just loads, before the template engine is created), add the following code:
>
> =============
> sub custom_filter(@) {
>          my $text = shift ;
>          $text = reverse $text;
>          return $text;
> }
> config->{engines}->{template_toolkit}->{FILTERS} = { 'my_custom_filter' =>  \&custom_filter } ;
> =============
>
> Then, I can use the following template code:
>    [% VAR | my_custom_filter %]
>
> It works thanks to the foresight of Dancer's developers (Thanks!!!) to pass-through all the config variables to template-toolkit's NEW.
>
> Note that this (Template Toolkit's static filters) can't be specified in the YML config file, because the value is not a string, it must be a code ref, so this needs to be done in your code.

config file:


engines:
   template_toolkit:
     extension: 'tt'
     PLUGIN_BASE: 'DA::Template::Plugin'


The filter code:

$ cat lib/DA/Template/Plugin/FormatDate.pm
package DA::Template::Plugin::FormatDate;

use Template::Plugin::Filter;
use base qw( Template::Plugin::Filter );

sub filter {
     my ($self, $text) = @_;
     $text =~ s/\s+\d{2}:\d{2}:\d{2}$//;
     return $text;
}

1;

How to use it on the template:

$ cat views/news.tt

<% USE FormatDate %>

<div id="main">
   <div class="text">
     <h2>Histórico de Novidades</h2>

     <dl>
       <% FOREACH new IN news %>
       <dt><% new.date | $FormatDate %> - <% new.title %></dt><dd><% 
new.text %></dd>
       <% END %>
     </dl>
   </div>
</div>

Hope this helps :)


More information about the Dancer-users mailing list