I have just finished two versions of a filter using HTML::FromText as
a backend.

The first version is a normal filter with preset defaults. (Presently
added to Template/Filters.pm)

use HTML::FromText;
sub html_fancy_filter_factory {
    my ($context, $args) = @_;
    my %args = ref $args eq 'HASH' ? %$args : ();

    $args{'paras'} = 1 unless exists $args{'paras'};
    $args{'urls'}  = 1 unless exists $args{'urls'};
    $args{'email'}  = 1 unless exists $args{'email'};
    $args{'bold'}  = 1 unless exists $args{'bold'};
    $args{'bullets'}  = 1 unless exists $args{'bullets'};
    $args{'numbers'}  = 1 unless exists $args{'numbers'};
    $args{'tables'}  = 1 unless exists $args{'tables'};
    $args{'blockparas'}  = 1 unless exists $args{'blockparas'};

    return sub {
        my $text = shift;
        $text = '' unless defined $text;

        return text2html($text, %args);
    }
}

This filter can be called with no parameters or with one or more
parameters, overriding each of the defaults provided above.



But then I thought that it would be better to specify the defaults
just one time, as with plugins.  So I made a plugin of the filter
(called Template::Plugin::HTML::FromText):

sub new {
    my $class   = shift;
    my $context = shift;
    my $args    = ref $_[-1] eq 'HASH' ? pop(@_) : {};


    $args->{'paras'} = 1 unless exists $args->{'paras'};
    $args->{'urls'}  = 1 unless exists $args->{'urls'};
    $args->{'email'}  = 1 unless exists $args->{'email'};
    $args->{'bold'}  = 1 unless exists $args->{'bold'};
    $args->{'bullets'}  = 1 unless exists $args->{'bullets'};
    $args->{'numbers'}  = 1 unless exists $args->{'numbers'};
    $args->{'tables'}  = 1 unless exists $args->{'tables'};
    $args->{'blockparas'}  = 1 unless exists $args->{'blockparas'};

    return bless $args, $class;
}

sub filter {
    my( $self ) = @_;
    return sub {
        my( $text ) = @_;
        $text = '' unless defined $text;
        return text2html($text, %$self);
    }
}


The plugin filter can be used like this:

    [% USE fancy = HTML.FromText( email = 0 ) %]

    <p>[% product.description | $fancy.filter %]</p>


Notice the extra '$' needed to dereference the filter.



I'm not enierly happy with any of these alternatives.  Can I do this
in a better way?  Will this (undocumented?) way to do filters continue
to be supported?


-- 
/ Jonas  -  http://jonas.liljegren.org/myself/en/index.html


Reply via email to