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;
23 my ($class, %params) = @_;
25 return $params{text} if ref($params{text}) eq $class;
27 my $self = bless {}, $class;
28 $self->{text} = $params{is_escaped} ? $params{text} : quote_html($params{text});
34 return undef unless defined $_[0];
35 (my $x = $_[0]) =~ s/(["'<>&])/$html_entities{$1}/ge;
40 __PACKAGE__->new(text => $_[0]);
44 __PACKAGE__->new(text => $_[0], is_escaped => 1);
54 __PACKAGE__->new(text => $text, is_escaped => 1);
76 SL::Presenter::EscapedText - Thin proxy object to invert the burden of escaping HTML output
80 use SL::Presenter::EscapedText qw(escape is_escaped escape_js);
84 return SL::Presenter::EscapedText->new(text => $text);
87 # return escape($text);
91 my $output_of_other_component = blackbox('Hello & Goodbye');
93 # The following is safe, text will not be escaped twice:
94 return SL::Presenter::EscapedText->new(text => $output_of_other_component);
97 my $output = build_output();
98 print "Yeah: $output\n";
102 Sometimes it's nice to let a sub-component build its own
103 representation. However, you always have to be very careful about
104 whose responsibility escaping is. Only the building function knows
105 enough about the structure to be able to HTML escape properly.
107 But higher functions should not have to care if the output is already
108 escaped -- they should be able to simply escape it again. Without
109 producing stuff like '&amp;'.
111 Stringification is overloaded. It will return the same as L<escaped_text>.
113 This works together with the template plugin
114 L<SL::Template::Plugin::P> and its C<escape> method.
122 Creates an instance of C<EscapedText>.
124 The parameter C<text> is the text to escape. If it is already an
125 instance of C<EscapedText> then C<$params{text}> is returned
128 Otherwise C<text> is HTML-escaped and stored in the new instance. This
129 can be overridden by setting C<$params{is_escaped}> to a trueish
132 =item C<escape $text>
134 Static constructor, can be exported. Equivalent to calling C<< new(text => $text) >>.
136 =item C<is_escaped $text>
138 Static constructor, can be exported. Equivalent to calling C<< new(text => $text, escaped => 1) >>.
140 =item C<escape_js $text>
142 Static constructor, can be exported. Like C<escape> but also escapes Javascript.
150 =item C<escaped_text>
152 Returns the escaped string (not an instance of C<EscapedText> but an
163 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>