X-Git-Url: http://wagnertech.de/gitweb/gitweb.cgi/mfinanz.git/blobdiff_plain/d445880375bce1462b8f9a8b1a502b34c296d41f..9cd5c461ba9556b2da3db71303930b6e41aa1dba:/SL/Presenter/EscapedText.pm diff --git a/SL/Presenter/EscapedText.pm b/SL/Presenter/EscapedText.pm index d482e8a30..2fc04fdeb 100644 --- a/SL/Presenter/EscapedText.pm +++ b/SL/Presenter/EscapedText.pm @@ -1,9 +1,16 @@ package SL::Presenter::EscapedText; use strict; +use Exporter qw(import); -use overload '""' => \&escaped; +our @EXPORT_OK = qw(escape is_escaped escape_js); +our %EXPORT_TAGS = (ALL => \@EXPORT_OK); +use JSON (); + +use overload '""' => \&escaped_text; + +# static constructors sub new { my ($class, %params) = @_; @@ -15,11 +22,34 @@ sub new { return $self; } -sub escaped { +sub escape { + __PACKAGE__->new(text => $_[0]); +} + +sub is_escaped { + __PACKAGE__->new(text => $_[0], is_escaped => 1); +} + +sub escape_js { + my ($text) = @_; + + $text =~ s|\\|\\\\|g; + $text =~ s|\"|\\\"|g; + $text =~ s|\n|\\n|g; + + __PACKAGE__->new(text => $text, is_escaped => 1); +} + +# internal magic +sub escaped_text { my ($self) = @_; return $self->{text}; } +sub TO_JSON { + goto &escaped_text; +} + 1; __END__ @@ -29,15 +59,18 @@ __END__ =head1 NAME -SL::Presenter::EscapedText - Thin proxy object around HTML-escaped strings +SL::Presenter::EscapedText - Thin proxy object to invert the burden of escaping HTML output =head1 SYNOPSIS - use SL::Presenter::EscapedText; + use SL::Presenter::EscapedText qw(escape is_escaped escape_js); sub blackbox { my ($text) = @_; return SL::Presenter::EscapedText->new(text => $text); + + # or shorter: + # return escape($text); } sub build_output { @@ -61,7 +94,7 @@ But higher functions should not have to care if the output is already escaped -- they should be able to simply escape it again. Without producing stuff like '&amp;'. -Stringification is overloaded. It will return the same as L. +Stringification is overloaded. It will return the same as L. This works together with the template plugin L and its C method. @@ -82,7 +115,25 @@ Otherwise C is HTML-escaped and stored in the new instance. This can be overridden by setting C<$params{is_escaped}> to a trueish value. -=item C +=item C + +Static constructor, can be exported. Equivalent to calling C<< new(text => $text) >>. + +=item C + +Static constructor, can be exported. Equivalent to calling C<< new(text => $text, escaped => 1) >>. + +=item C + +Static constructor, can be exported. Like C but also escapes Javascript. + +=back + +=head1 METHODS + +=over 4 + +=item C Returns the escaped string (not an instance of C but an actual string).