Line 0
Link Here
|
|
|
1 |
# |
2 |
# $Id: TruncateByWord.pm,v 1.3 2008/06/20 06:17:12 oneroad Exp $ |
3 |
# |
4 |
package Koha::Template::Plugin::TruncateByWord; |
5 |
|
6 |
use strict; |
7 |
use warnings; |
8 |
|
9 |
our $VERSION = '0.11'; |
10 |
|
11 |
use Template::Plugin::Filter; |
12 |
use base 'Template::Plugin::Filter'; |
13 |
|
14 |
use Encode; |
15 |
|
16 |
our $FILTER_NAME_DEFAULT = 'truncate_by_word'; |
17 |
our $ORG_ENC_DEFAULT = 'utf8'; |
18 |
|
19 |
sub init { |
20 |
my $self = shift; |
21 |
$self->{_DYNAMIC} = 1; |
22 |
$self->install_filter($self->{_CONFIG}->{name}||$FILTER_NAME_DEFAULT); |
23 |
$self->{_CONFIG}->{enc} ||= $self->{_ARGS}->[0] || $ORG_ENC_DEFAULT; |
24 |
return $self; |
25 |
} |
26 |
|
27 |
sub filter { |
28 |
my($self, $string, $args, $conf) = @_; |
29 |
|
30 |
return '' unless $string; |
31 |
|
32 |
# decode |
33 |
my $org_enc; |
34 |
unless ( utf8::is_utf8($string) ) { |
35 |
$org_enc = $self->{_CONFIG}->{enc}; |
36 |
$string = Encode::decode($org_enc, $string); |
37 |
} |
38 |
|
39 |
my $org_length = CORE::length($string); |
40 |
my $length = $args->[0] || $org_length; |
41 |
return if $length =~ /\D/; |
42 |
$string = CORE::substr($string, 0, $length); |
43 |
|
44 |
my $suffix = $args->[1]||''; |
45 |
# revive encode |
46 |
$string = Encode::encode($org_enc, $string) if $org_enc; |
47 |
return $org_length > $length ? $string.$suffix : $string ; |
48 |
} |
49 |
|
50 |
1; |
51 |
__END__ |
52 |
|
53 |
=head1 NAME |
54 |
|
55 |
Template::Plugin::TruncateByWord - A Template Toolkit filter to truncate not the number of bytes but characters |
56 |
|
57 |
=head1 SYNOPSIS |
58 |
|
59 |
# result is 'ab' |
60 |
[% USE TruncateByWord %] |
61 |
[% 'abcdefg' | truncate_by_word(2) %] |
62 |
|
63 |
# result is 'abc....' |
64 |
[% USE TruncateByWord %] |
65 |
[% FILTER truncate_by_word(3,'....') %] |
66 |
abcdefg |
67 |
[% END %] |
68 |
|
69 |
# default charset = 'utf8'. you can change this. |
70 |
# result is 'abcd' |
71 |
[% USE TruncateByWord 'euc-jp' %] |
72 |
[% FILTER truncate_by_word(4) %] |
73 |
abcdefg |
74 |
[% END %] |
75 |
|
76 |
=head1 DESCRIPTION |
77 |
|
78 |
Template::Plugin::TruncateByWord is a filter plugin for Template Toolkit which truncate text not the number of bytes but the number of characters. |
79 |
|
80 |
=head1 BUGS |
81 |
|
82 |
If found, please Email me. I tested utf8, euc-jp, shiftjis, 7bit-jis, big5, and euc-kr. Please send me more test cases. |
83 |
|
84 |
=head1 SEE ALSO |
85 |
|
86 |
L<Template>, L<Template::Plugin::Filter>, and t/*.t |
87 |
|
88 |
=head1 AUTHOR |
89 |
|
90 |
User & KAWABATA Kazumichi (Higemaru) E<lt>kawabata@cpan.orgE<gt> |
91 |
|
92 |
=head1 COPYRIGHT AND LICENSE |
93 |
|
94 |
Copyright (C) 2008- KAWABATA Kazumichi |
95 |
|
96 |
This library is free software; you can redistribute it and/or modify |
97 |
it under the same terms as Perl itself. |
98 |
|
99 |
|
100 |
=cut |