Template::Plugin::TruncateByWord (3)

Template::Plugin::TruncateByWord (3) #

こんなもんでいいか

 package Template::Plugin::TruncateByWord;
 
 use strict;
 use warnings;
 
 our $VERSION = '0.1';
 
 use Template::Plugin::Filter;
 use base 'Template::Plugin::Filter';
 
 use Encode;
 
 our $FILTER_NAME_DEFAULT = 'truncate_by_word';
 our $ORG_ENC_DEFAULT = 'utf8';
 
 sub init {
     my $self = shift;
     $self->{_DYNAMIC} = 1;
     $self->install_filter($self->{_CONFIG}->{name}||$FILTER_NAME_DEFAULT);
     $self->{_CONFIG}->{enc} ||= $self->{_ARGS}->[0] || $ORG_ENC_DEFAULT;
     return $self;
 }
 
 sub filter {
     my($self, $string, $args, $conf) = @_;
 
     return '' unless $string;
 
     # decode
     my $org_enc;
     unless ( utf8::is_utf8($string) ) {
         $org_enc = $self->{_CONFIG}->{enc};
         $string = Encode::decode($org_enc, $string);
     }
 
     my $org_length = CORE::length($string);
     my $length = $args->[0] || $org_length;
     return if $length =~ /\\D/;
     $string = CORE::substr($string, 0, $length);
 
     my $suffix = $args->[1]||'';
     # revive encode
     $string = Encode::encode($org_enc, $string) if $org_enc;
     return $org_length > $length ? $string.$suffix : $string ;
 }
 
 1;

See Also

Copyright © 髭。/ Hugo + hugo-book