Wednesday, April 05, 2006

Template Plugin HtmlToText

It's a TT plugin for format html to text, a plugin interface to HTML::FormatText.

将 HTML 用 HTML::FormatText 转为 Text 文本。

Template::Plugin::HtmlToText is a easy plugin, all code is here:
package Template::Plugin::HtmlToText;

use strict;
use vars qw( @ISA $VERSION );
use base qw( Template::Plugin );
use Template::Plugin;

$VERSION = '0.01';

sub new {
my ($class, $context, $arg) = @_;
$context->define_filter('html2text', [ \&html2text => 1 ]);
return \&tt_wrap;
}

sub html2text {
my ($context, $args) = @_;
return sub {
my $html = shift;
return $html unless ($html =~ m#(<|>)#s);

require HTML::TreeBuilder;
my $tree = HTML::TreeBuilder->new->parse($html);
require HTML::FormatText;
my $formatter = HTML::FormatText->new(%{$args});
my $text = $formatter->format($tree);
return $text;
}
}

1;

0 Comments:

Post a Comment

<< Home