c28ae28fd215095357d4d2c3d868a3781a50ad3a
[scpubgit/HTML-String.git] / lib / HTML / String / TT / Directive.pm
1 package HTML::String::TT::Directive;
2
3 use strictures 1;
4 use HTML::String::Overload ();
5 use Data::Munge;
6 use base qw(Template::Directive);
7
8 sub template {
9     return byval {
10         s/sub {/sub { package HTML::String::TT::_TMPL; use HTML::String::Overload { ignore => { q{Template::Provider} => 1, q{Template::Directive} => 1, q{Template::Document} => 1, q{Template::Plugins} => 1 } };/;
11     } Template::Directive::pad(shift->SUPER::template(@_), 2);
12 }
13
14 # TT code does &text(), no idea why
15
16 sub textblock {
17     my ($self, $text) = @_;
18     return $Template::Directive::OUTPUT.' '.$self->text($text).';';
19 }
20
21 # https://rt.perl.org/rt3/Ticket/Display.html?id=49594
22
23 sub text {
24     my ($class, $text) = @_;
25     for ($text) {
26         s/(["\$\@\\])/"."\\$1"."/g;
27         s/\n/"."\\n"."/g;
28     }
29     return '"' . $text . '"';
30 }
31
32 1;
33
34 __END__
35
36 =head1 NAME
37
38 HTML::String::TT::Directive - L<Template::Directive> overrides to forcibly escape HTML strings
39
40 =head1 SYNOPSIS
41
42 This is not user serviceable, and is documented only for your edification.
43
44 Please use L<HTML::String::TT> as this module could change, be renamed, or
45 if I figure out a better way of implementing the functionality disappear
46 entirely at any moment.
47
48 =head1 METHODS
49
50 =head2 template
51
52 We override this top-level method in order to pretend two things to the
53 perl subroutine definition that TT has generated - firstly,
54
55   package HTML::String::TT::_TMPL;
56
57 to ensure that no packages marked to be ignored are the current one when
58 the template code is executed. Secondly,
59
60   use HTML::String::Overload { ignore => { ... } };
61
62 where the C<...> contains a list of TT internal packages to ignore so that
63 things actually work. This list is not duplicated here since it may also
64 change without warning.
65
66 Additionally, the hashref option to L<HTML::String::Overload> is not
67 documented there since I'm not yet convinced that's a public API either.
68
69 =head2 text
70
71 Due to a perl bug (L<https://rt.perl.org/rt3/Ticket/Display.html?id=49594>)
72 we overload this method to change
73
74   "<foo>\n<bar>"
75
76 into
77
78   "<foo>"."\n"."<bar>"
79
80 since any string containing a backslash escape doesn't get marked as HTML.
81 Since we don't want to escape things that backslash escapes are normally
82 used for, this isn't really a problem for us.
83
84 =head2 textblock
85
86 For no reason I can comprehend at all, L<Template::Directive>'s C<textblock>
87 method calls C<&text> instead of using a method call so we have to override
88 this as well.
89
90 =head1 AUTHORS
91
92 See L<HTML::String> for authors.
93
94 =head1 COPYRIGHT AND LICENSE
95
96 See L<HTML::String> for the copyright and license.
97
98 =cut