bcae2f96f4ceb5fa0f2678f410543f38b39bca90
[kivitendo-erp.git] / SL / Presenter / Text.pm
1 package SL::Presenter::Text;
2
3 use strict;
4
5 use parent qw(Exporter);
6
7 use Exporter qw(import);
8 our @EXPORT = qw(simple_format truncate);
9
10 use Carp;
11
12 sub truncate {
13   my ($self, $text, %params) = @_;
14
15   $params{at}             ||= 50;
16   $params{at}               =  3 if 3 > $params{at};
17   $params{at}              -= 3;
18
19   return $text if length($text) < $params{at};
20   return substr($text, 0, $params{at}) . '...';
21 }
22
23 sub simple_format {
24   my ($self, $text, %params) = @_;
25
26   $text =  $::locale->quote_special_chars('HTML', $text || '');
27
28   $text =~ s{\r\n?}{\n}g;                    # \r\n and \r -> \n
29   $text =~ s{\n\n+}{</p>\n\n<p>}g;           # 2+ newline  -> paragraph
30   $text =~ s{([^\n]\n)(?=[^\n])}{$1<br />}g; # 1 newline   -> br
31
32   return '<p>' . $text;
33 }
34
35 1;
36 __END__
37
38 =pod
39
40 =encoding utf8
41
42 =head1 NAME
43
44 SL::Presenter::Text - Presenter module for assorted text helpers
45
46 =head1 SYNOPSIS
47
48   my $long_text = "This is very, very long. Need shorter, surely.";
49   my $truncated = $::request->presenter->truncate($long_text, at => 10);
50   # Result: "This is..."
51
52 =head1 FUNCTIONS
53
54 =over 4
55
56 =item C<truncate $text, [%params]>
57
58 Returns the C<$text> truncated after a certain number of
59 characters.
60
61 The number of characters to truncate at is determined by the parameter
62 C<at> which defaults to 50. If the text is longer than C<$params{at}>
63 then it will be truncated and postfixed with '...'. Otherwise it will
64 be returned unmodified.
65
66 =item C<simple_format $text>
67
68 Applies simple formatting rules to C<$text>: The text is put into
69 paragraph HTML tags. Two consecutive newlines are interpreted as a
70 paragraph change: they close the current paragraph tag and start a new
71 one. Single newlines are converted to line breaks. Carriage returns
72 are removed.
73
74 =back
75
76 =head1 BUGS
77
78 Nothing here yet.
79
80 =head1 AUTHOR
81
82 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
83
84 =cut