1 package SL::Presenter::EscapedText;
4 use Exporter qw(import);
6 our @EXPORT_OK = qw(escape is_escaped escape_js);
7 our %EXPORT_TAGS = (ALL => \@EXPORT_OK);
11 use overload '""' => \&escaped_text;
15 my ($class, %params) = @_;
17 return $params{text} if ref($params{text}) eq $class;
19 my $self = bless {}, $class;
20 $self->{text} = $params{is_escaped} ? $params{text} : $::locale->quote_special_chars('HTML', $params{text});
26 __PACKAGE__->new(text => $_[0]);
30 __PACKAGE__->new(text => $_[0], is_escaped => 1);
40 __PACKAGE__->new(text => $text, is_escaped => 1);
62 SL::Presenter::EscapedText - Thin proxy object to invert the burden of escaping HTML output
66 use SL::Presenter::EscapedText qw(escape is_escaped escape_js);
70 return SL::Presenter::EscapedText->new(text => $text);
73 # return escape($text);
77 my $output_of_other_component = blackbox('Hello & Goodbye');
79 # The following is safe, text will not be escaped twice:
80 return SL::Presenter::EscapedText->new(text => $output_of_other_component);
83 my $output = build_output();
84 print "Yeah: $output\n";
88 Sometimes it's nice to let a sub-component build its own
89 representation. However, you always have to be very careful about
90 whose responsibility escaping is. Only the building function knows
91 enough about the structure to be able to HTML escape properly.
93 But higher functions should not have to care if the output is already
94 escaped -- they should be able to simply escape it again. Without
95 producing stuff like '&'.
97 Stringification is overloaded. It will return the same as L<escaped_text>.
99 This works together with the template plugin
100 L<SL::Template::Plugin::P> and its C<escape> method.
108 Creates an instance of C<EscapedText>.
110 The parameter C<text> is the text to escape. If it is already an
111 instance of C<EscapedText> then C<$params{text}> is returned
114 Otherwise C<text> is HTML-escaped and stored in the new instance. This
115 can be overridden by setting C<$params{is_escaped}> to a trueish
118 =item C<escape $text>
120 Static constructor, can be exported. Equivalent to calling C<< new(text => $text) >>.
122 =item C<is_escaped $text>
124 Static constructor, can be exported. Equivalent to calling C<< new(text => $text, escaped => 1) >>.
126 =item C<escape_js $text>
128 Static constructor, can be exported. Like C<escape> but also escapes Javascript.
136 =item C<escaped_text>
138 Returns the escaped string (not an instance of C<EscapedText> but an
149 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>